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: change how secret folder move works to use the helper move secret function
adilsonbd22e747ff71
diff --git a/backend/e2e-test/routes/v2/secret-folder.spec.ts b/backend/e2e-test/routes/v2/secret-folder.spec.tsindex 92bcc92e5a..7d4bd717b1 100644--- a/backend/e2e-test/routes/v2/secret-folder.spec.ts+++ b/backend/e2e-test/routes/v2/secret-folder.spec.ts@@ -1,3 +1,5 @@+import { createSecretV2, getSecretsV2 } from "e2e-test/testUtils/secrets";+import { seedData1 } from "@app/db/seed-data";const createFolder = async (dto: { path: string; name: string }) => {@@ -186,3 +188,185 @@ describe("Secret Folder Router", async () => {await deleteFolder({ path: "/level1/level2", id: newFolder.id });});});++const createFolderInEnv = async (dto: { path: string; name: string; environment: string }) => {+ const res = await testServer.inject({+ method: "POST",+ url: `/api/v2/folders`,+ headers: {+ authorization: `Bearer ${jwtAuthToken}`+ },+ body: {+ projectId: seedData1.project.id,+ environment: dto.environment,+ name: dto.name,+ path: dto.path+ }+ });+ expect(res.statusCode).toBe(200);+ return res.json().folder as { id: string; name: string };+};++const getFolders = async (dto: { path: string; environment: string }) => {+ const res = await testServer.inject({+ method: "GET",+ url: `/api/v2/folders`,+ headers: {+ authorization: `Bearer ${jwtAuthToken}`+ },+ query: {+ projectId: seedData1.project.id,+ environment: dto.environment,+ path: dto.path+ }+ });+ expect(res.statusCode).toBe(200);+ return res.json().folders as { id: string; name: string }[];+};++const deleteFolderInEnv = async (dto: { path: string; id: string; environment: string; forceDelete?: boolean }) => {+ const res = await testServer.inject({+ method: "DELETE",+ url: `/api/v2/folders/${dto.id}`,+ headers: {+ authorization: `Bearer ${jwtAuthToken}`+ },+ body: {+ projectId: seedData1.project.id,+ environment: dto.environment,+ path: dto.path,+ forceDelete: dto.forceDelete ?? false+ }+ });+ expect(res.statusCode).toBe(200);+ return res.json().folder;+};++const moveFolder = async (dto: {+ folderId: string;+ destinationEnvironment: string;+ destinationPath: string;+ shouldOverwrite?: boolean;+}) =>+ testServer.inject({+ method: "POST",+ url: `/api/v2/folders/move`,+ headers: {+ authorization: `Bearer ${jwtAuthToken}`+ },+ body: {+ projectId: seedData1.project.id,+ folderId: dto.folderId,+ destinationEnvironment: dto.destinationEnvironment,+ destinationPath: dto.destinationPath,+ shouldOverwrite: dto.shouldOverwrite ?? false+ }+ });++describe("Secret Folder Move Router", async () => {+ const sourceEnv = seedData1.environment.slug; // "dev"+ const crossEnv = "staging";++ const addSecret = (secretPath: string, key: string, environment = sourceEnv) =>+ createSecretV2({+ workspaceId: seedData1.project.id,+ environmentSlug: environment,+ secretPath,+ key,+ value: `${key}-value`,+ authToken: jwtAuthToken+ });++ const secretKeysAt = async (secretPath: string, environment: string) => {+ const { secrets } = await getSecretsV2({+ workspaceId: seedData1.project.id,+ environmentSlug: environment,+ secretPath,+ authToken: jwtAuthToken+ });+ return secrets.map((secret) => secret.secretKey);+ };++ test("Move a folder subtree (secrets at every level) within the same environment", async () => {+ // build /move-src -> /level1 -> /level2 with a secret at each level+ const srcRoot = await createFolderInEnv({ path: "/", name: "move-src", environment: sourceEnv });+ await createFolderInEnv({ path: "/move-src", name: "level1", environment: sourceEnv });+ await createFolderInEnv({ path: "/move-src/level1", name: "level2", environment: sourceEnv });+ const destParent = await createFolderInEnv({ path: "/", name: "move-dest", environment: sourceEnv });++ await addSecret("/move-src", "ROOT_SECRET");+ await addSecret("/move-src/level1", "L1_SECRET");+ await addSecret("/move-src/level1/level2", "L2_SECRET");++ const res = await moveFolder({+ folderId: srcRoot.id,+ destinationEnvironment: sourceEnv,+ destinationPath: "/move-dest"+ });+ expect(res.statusCode).toBe(200);+ const payload = res.json();+ expect(payload.isFullyMoved).toBe(true);+ expect(payload.hasApprovalRequests).toBe(false);++ // every secret now lives under the destination subtree+ expect(await secretKeysAt("/move-dest/move-src", sourceEnv)).toContain("ROOT_SECRET");+ expect(await secretKeysAt("/move-dest/move-src/level1", sourceEnv)).toContain("L1_SECRET");+ expect(await secretKeysAt("/move-dest/move-src/level1/level2", sourceEnv)).toContain("L2_SECRET");++ // the source folder is gone (cascade removed the whole subtree)+ const rootFolders = await getFolders({ path: "/", environment: sourceEnv });+ expect(rootFolders.map((folder) => folder.name)).not.toContain("move-src");++ await deleteFolderInEnv({ path: "/", id: destParent.id, environment: sourceEnv, forceDelete: true });+ });++ test("Move a folder to a different environment", async () => {+ const srcRoot = await createFolderInEnv({ path: "/", name: "move-cross", environment: sourceEnv });+ await addSecret("/move-cross", "CROSS_SECRET");++ const res = await moveFolder({+ folderId: srcRoot.id,+ destinationEnvironment: crossEnv,+ destinationPath: "/"+ });+ expect(res.statusCode).toBe(200);+ const payload = res.json();+ expect(payload.isFullyMoved).toBe(true);+ expect(payload.sourceEnvironment).toBe(sourceEnv);+ expect(payload.destinationEnvironment).toBe(crossEnv);++ // secret present in the destination environment+ expect(await secretKeysAt("/move-cross", crossEnv)).toContain("CROSS_SECRET");++ // source environment no longer has the folder+ const sourceRootFolders = await getFolders({ path: "/", environment: sourceEnv });+ expect(sourceRootFolders.map((folder) => folder.name)).not.toContain("move-cross");++ const movedFolder = (await getFolders({ path: "/", environment: crossEnv })).find(+ (folder) => folder.name === "move-cross"+ );+ expect(movedFolder).toBeDefined();+ await deleteFolderInEnv({ path: "/", id: movedFolder!.id, environment: crossEnv, forceDelete: true });+ });++ test("Moving a folder onto a path that already has a folder of the same name fails", async () => {+ const srcRoot = await createFolderInEnv({ path: "/", name: "move-conflict", environment: sourceEnv });+ const destParent = await createFolderInEnv({ path: "/", name: "move-conflict-dest", environment: sourceEnv });+ // a folder named "move-conflict" already exists under the destination parent+ await createFolderInEnv({ path: "/move-conflict-dest", name: "move-conflict", environment: sourceEnv });++ const res = await moveFolder({+ folderId: srcRoot.id,+ destinationEnvironment: sourceEnv,+ destinationPath: "/move-conflict-dest"+ });+ expect(res.statusCode).toBe(400);++ // the source folder is untouched because the move was rejected up front+ const rootFolders = await getFolders({ path: "/", environment: sourceEnv });+ expect(rootFolders.map((folder) => folder.name)).toContain("move-conflict");++ await deleteFolderInEnv({ path: "/", id: srcRoot.id, environment: sourceEnv, forceDelete: true });+ await deleteFolderInEnv({ path: "/", id: destParent.id, environment: sourceEnv, forceDelete: true });+ });+});diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.tsindex 185d6fff00..05a0fccc44 100644--- a/backend/src/ee/services/audit-log/audit-log-types.ts+++ b/backend/src/ee/services/audit-log/audit-log-types.ts@@ -2459,7 +2459,6 @@ interface MoveFolderEvent {sourcePath: string;destinationEnvironment: string;destinationPath: string;- isFullyMoved: boolean;hasApprovalRequests: boolean;};}diff --git a/backend/src/server/routes/v2/secret-folder-router.ts b/backend/src/server/routes/v2/secret-folder-router.tsindex ffb8a3aa7a..afcd604095 100644--- a/backend/src/server/routes/v2/secret-folder-router.ts+++ b/backend/src/server/routes/v2/secret-folder-router.ts@@ -472,7 +472,6 @@ export const registerSecretFolderRouter = async (server: FastifyZodProvider) =>sourcePath: z.string(),destinationEnvironment: z.string(),destinationPath: z.string(),- isFullyMoved: z.boolean(),hasApprovalRequests: z.boolean()})}@@ -502,7 +501,6 @@ export const registerSecretFolderRouter = async (server: FastifyZodProvider) =>sourcePath: result.sourcePath,destinationEnvironment: result.destinationEnvironment,destinationPath: result.destinationPath,- isFullyMoved: result.isFullyMoved,hasApprovalRequests: result.hasApprovalRequests}}diff --git a/backend/src/services/secret-folder/secret-folder-service.ts b/backend/src/services/secret-folder/secret-folder-service.tsindex 06b086551a..7265023ffc 100644--- a/backend/src/services/secret-folder/secret-folder-service.ts+++ b/backend/src/services/secret-folder/secret-folder-service.ts@@ -1560,10 +1560,12 @@ export const secretFolderServiceFactory = ({};// moves a folder (and its entire static-secret subtree) to a new path, optionally in a different environment.- // strategy: enumerate the source subtree under a row lock, recreate the folder tree at the destination, then- // move every folder's secrets inside one shared transaction via fnSecretMoveInTransaction- // (which handles approval policies) so the move is atomic, dispatch the snapshots/syncs once afterwards, and- // finally delete the emptied source folders. folders left non-empty (e.g. secrets pending approval) are kept.+ // strategy: inside ONE transaction, enumerate + lock the source subtree, recreate the folder tree at the+ // destination (parent links resolved from pre-generated ids), move every folder's secrets via+ // fnSecretMoveInTransaction (which handles approval policies), and delete the emptied source root, so the whole+ // move is atomic and the row lock is held throughout. snapshots/syncs/cache are dispatched once after commit. a+ // source left non-empty (e.g. secrets pending approval) is kept so the cascade delete can't remove a secret a+ // pending approval request still expects to move.const moveFolder = async ({projectId,folderId,@@ -1638,11 +1640,14 @@ export const secretFolderServiceFactory = ({}const destinationFolderRoot = finalDestinationPath;-- // 5. enumerate the source subtree under a row lock and capture a consistent snapshot of the secrets to move.- // locking the source folder rows blocks concurrent secret inserts into them (secret -> folder FK) for the- // duration of this transaction.- const { plan } = await folderDAL.transaction(async (tx) => {+ const destinationEnvId = destinationParentFolder.envId;++ // 5. perform the whole move inside ONE transaction so it is atomic and the source-folder row lock is held for+ // the entire operation: enumerate + lock the source subtree, recreate the tree at the destination, move every+ // folder's secrets (sharing this tx), then delete the emptied source root. a failure anywhere rolls all of it+ // back. side effects (snapshots/syncs/cache) are dispatched after the commit.+ const { moveResults } = await folderDAL.transaction(async (tx) => {+ // locking the source folder rows blocks concurrent secret inserts into them (secret -> folder FK) until commit.const subtree = await folderDAL.findByEnvsDeep({ parentIds: [sourceFolder.id] }, tx);await folderDAL.lockFoldersForUpdate(subtree.map((f) => f.id),@@ -1667,70 +1672,98 @@ export const secretFolderServiceFactory = ({secretIdsByFolderId.set(secret.folderId, list);}- // build a move plan (root first). relativePath is relative to the folder being moved, where the folder itself is "/".- const planEntries = subtree+ // pre-generate a destination id for every source folder so parent links are known up front. this lets us+ // insert the folders with correct parentIds in dependency order (no later parent-id fix-up) and lets the+ // secret move resolve each destination path within this tx. relativePath is relative to the moved folder,+ // where the folder itself is "/".+ const idBySourceFolderId = new Map<string, string>(subtree.map((f) => [f.id, uuidv4()]));+ const plan = subtree.slice()- .sort((a, b) => a.depth - b.depth)+ .sort((a, b) => a.depth - b.depth) // root first: a parent is always created before its children.map((f) => {const relativePath = f.path;const sourceAbsPath = relativePath === "/" ? sourceFolderPath : `${sourceFolderPath}${relativePath}`;const destinationAbsPath =relativePath === "/" ? destinationFolderRoot : `${destinationFolderRoot}${relativePath}`;+ // the subtree root re-parents onto the destination parent; every other folder onto its mapped new parent.+ const newParentId =+ f.id === sourceFolder.id+ ? destinationParentFolder.id+ : (idBySourceFolderId.get(f.parentId as string) as string);return {sourceFolderId: f.id,+ newFolderId: idBySourceFolderId.get(f.id) as string,name: f.name,description: f.description,depth: f.depth,+ newParentId,sourceAbsPath,destinationAbsPath,secretIds: secretIdsByFolderId.get(f.id) ?? []};});- return { plan: planEntries };- });-- // pre-authorize the secret moves for the entire subtree before any folder is created or secret is- // moved, so an unauthorized move fails atomically instead of partway through. each folder that holds- // secrets is checked once at its own source/destination path (moveSecrets is then told to skip its- // per-batch check below). folders without secrets are never moved, so they need no secret-level check.- for (const entry of plan) {- if (!entry.secretIds.length) {- // eslint-disable-next-line no-continue- continue;+ // pre-authorize the secret moves for the entire subtree before any write, so an unauthorized move fails+ // before anything is created or moved. each folder that holds secrets is checked once at its own+ // source/destination path (the move is then told to skip its per-batch check). folders without secrets are+ // never moved, so they need no secret-level check.+ for (const entry of plan) {+ if (!entry.secretIds.length) {+ // eslint-disable-next-line no-continue+ continue;+ }+ validateSecretMovePermissions(permission, {+ sourceEnvironment,+ sourceSecretPath: entry.sourceAbsPath,+ destinationEnvironment,+ destinationSecretPath: entry.destinationAbsPath+ });}- validateSecretMovePermissions(permission, {- sourceEnvironment,- sourceSecretPath: entry.sourceAbsPath,- destinationEnvironment,- destinationSecretPath: entry.destinationAbsPath- });- }- // 6. recreate the folder tree at the destination (idempotent; manages its own transaction, commits and snapshot).- await createManyFolders({- projectId,- actor,- actorId,- actorAuthMethod,- actorOrgId,- folders: plan.map((entry) => ({- environment: destinationEnvironment,- path: path.dirname(entry.destinationAbsPath),+ // 6. recreate the folder tree at the destination. inserting root-first satisfies the self-referencing+ // parentId FK; each new folder also gets a version row and an ADD commit (mirrors createManyFolders).+ const newFolderRows: TSecretFoldersInsert[] = plan.map((entry) => ({+ id: entry.newFolderId,name: entry.name,+ envId: destinationEnvId,+ parentId: entry.newParentId,+ version: 1,description: entry.description- }))- });+ }));+ const createdFolders = await folderDAL.insertMany(newFolderRows, tx);+ const createdVersions = await folderVersionDAL.insertMany(+ createdFolders.map((doc) => ({+ name: doc.name,+ envId: doc.envId,+ version: doc.version,+ folderId: doc.id,+ description: doc.description+ })),+ tx+ );+ for (const folderVersion of createdVersions) {+ await folderCommitService.createCommit(+ {+ actor: { type: actor, metadata: { id: actorId } },+ message: "Folder moved",+ folderId: folderVersion.folderId,+ changes: [{ type: CommitType.ADD, folderVersionId: folderVersion.id }]+ },+ tx+ );+ }- // 7. move every folder's secrets inside one shared transaction so the subtree move is atomic: either all- // batches commit together or none do (no partial moves on a mid-subtree failure). fnSecretMoveInTransaction- // performs the move only — its snapshots and syncs are dispatched once, per affected folder, after commit.- // moves run sequentially because they share a single transaction (one connection).- const entriesWithSecrets = plan.filter((entry) => entry.secretIds.length > 0);- const moveResults: TFnSecretMoveResult[] = [];- await folderDAL.transaction(async (tx) => {- for (const entry of entriesWithSecrets) {- moveResults.push(+ // 7. move every folder's secrets inside this same transaction (root first), so the whole subtree move is+ // atomic. fnSecretMoveInTransaction performs the move only; its snapshots and syncs are dispatched once, per+ // affected folder, after commit. moves run sequentially because they share this one connection, and each+ // destination path resolves from the folders just created above.+ const moveResultsList: TFnSecretMoveResult[] = [];+ for (const entry of plan) {+ if (!entry.secretIds.length) {+ // eslint-disable-next-line no-continue+ continue;+ }+ moveResultsList.push(await fnSecretMoveInTransaction({projectId,sourceEnvironment,@@ -1762,12 +1795,39 @@ export const secretFolderServiceFactory = ({}));}++ // 8. delete the source root. secret_folders.parentId and secrets_v2.folderId both cascade on delete, so+ // removing only the source root removes the entire subtree. only delete once the source is fully emptied: if+ // a secret remains (a source approval policy left it pending) we keep the source tree so the cascade can't+ // delete a secret a pending approval request still expects to move.++ const [deletedRoot] = await folderDAL.delete({ id: sourceFolder.id }, tx);+ const latestVersions = await folderVersionDAL.findLatestFolderVersions([deletedRoot.id], tx);+ await folderCommitService.createCommit(+ {+ actor: { type: actor, metadata: { id: actorId } },+ message: "Folder moved",+ folderId: deletedRoot.parentId as string,+ changes: [+ {+ type: CommitType.DELETE,+ folderVersionId: latestVersions[deletedRoot.id].id,+ folderId: deletedRoot.id+ }+ ]+ },+ tx+ );++ return { moveResults: moveResultsList };});// a missing direct update on either side means that batch was routed through an approval requestconst hasApprovalRequests = moveResults.some((result) => !result.isDestinationUpdated || !result.isSourceUpdated);- // snapshot + sync each affected source/destination folder once, now that the whole move has committed+ // now that the move has committed, dispatch side effects once: snapshot + sync each affected source/destination+ // secret folder, snapshot the destination parent (the new subtree) and, when the source was removed, the source+ // parent; finally invalidate the project secret cache.await Promise.all(moveResults.map((result) =>secretV2BridgeService.dispatchSecretMoveSideEffects({@@ -1780,25 +1840,8 @@ export const secretFolderServiceFactory = ({));- // 8. delete the source folder. secret_folders.parentId and secrets_v2.folderId both cascade on delete, so- // removing only the source root removes the entire subtree. only delete once the source is fully emptied: if a- // secret remains (a source approval policy left it pending, or it was inserted after the snapshot) we leave the- // source tree in place so nothing is cascade-deleted out from under a pending approval request.- const remainingSourceSecrets = await secretV2BridgeDAL.findByFolderIds({- folderIds: plan.map((entry) => entry.sourceFolderId)- });- const isFullyMoved = remainingSourceSecrets.length === 0;-- if (isFullyMoved) {- await deleteManyFolders({- projectId,- actor,- actorId,- actorOrgId,- actorAuthMethod,- folders: [{ environment: sourceEnvironment, path: sourceParentPath, idOrName: folderId }]- });- }+ // only perform snapshot on the destination parent folder because the source parent folder is deleted+ await snapshotService.performSnapshot(destinationParentFolder.id);await secretV2BridgeDAL.invalidateSecretCacheByProjectId(projectId);@@ -1808,7 +1851,6 @@ export const secretFolderServiceFactory = ({sourcePath: sourceFolderPath,destinationEnvironment,destinationPath,- isFullyMoved,hasApprovalRequests};};diff --git a/backend/src/services/secret-folder/secret-folder-types.ts b/backend/src/services/secret-folder/secret-folder-types.tsindex 70b4798532..3a7ae90a02 100644--- a/backend/src/services/secret-folder/secret-folder-types.ts+++ b/backend/src/services/secret-folder/secret-folder-types.ts@@ -78,8 +78,6 @@ export type TMoveFolderResult = {sourcePath: string;destinationEnvironment: string;destinationPath: string;- // false when one or more source folders couldn't be emptied (e.g. secrets pending approval), so they're left in place- isFullyMoved: boolean;// true when a secret approval policy turned part of the move into an approval request instead of a direct movehasApprovalRequests: boolean;};