Skip to content

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

feat: add initial move folders into secret-folder-service

adilson3fae04e2e317
diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.ts
index faea68bbaa..185d6fff00 100644
--- a/backend/src/ee/services/audit-log/audit-log-types.ts
+++ b/backend/src/ee/services/audit-log/audit-log-types.ts
@@ -320,6 +320,7 @@ export enum EventType {
CREATE_FOLDER = "create-folder",
UPDATE_FOLDER = "update-folder",
DELETE_FOLDER = "delete-folder",
+ MOVE_FOLDER = "move-folder",
CREATE_WEBHOOK = "create-webhook",
UPDATE_WEBHOOK_STATUS = "update-webhook-status",
DELETE_WEBHOOK = "delete-webhook",
@@ -2450,6 +2451,19 @@ interface DeleteFolderEvent {
};
}
+interface MoveFolderEvent {
+ type: EventType.MOVE_FOLDER;
+ metadata: {
+ folderId: string;
+ sourceEnvironment: string;
+ sourcePath: string;
+ destinationEnvironment: string;
+ destinationPath: string;
+ isFullyMoved: boolean;
+ hasApprovalRequests: boolean;
+ };
+}
+
interface CreateWebhookEvent {
type: EventType.CREATE_WEBHOOK;
metadata: {
@@ -7436,6 +7450,7 @@ export type Event =
| CreateFolderEvent
| UpdateFolderEvent
| DeleteFolderEvent
+ | MoveFolderEvent
| CreateWebhookEvent
| UpdateWebhookStatusEvent
| DeleteWebhookEvent
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index d0e41dfed8..feccbf83d6 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -1861,22 +1861,6 @@ export const registerRoutes = async (
secretDAL: secretV2BridgeDAL,
secretVersionV2BridgeDAL
});
- const folderService = secretFolderServiceFactory({
- permissionService,
- folderDAL,
- folderVersionDAL,
- projectEnvDAL,
- snapshotService,
- projectDAL,
- folderCommitService,
- secretApprovalPolicyService,
- secretV2BridgeDAL,
- dynamicSecretDAL,
- secretRotationV2DAL,
- honeyTokenDAL,
- secretImportDAL
- });
-
const secretImportService = secretImportServiceFactory({
licenseService,
projectBotService,
@@ -1981,6 +1965,23 @@ export const registerRoutes = async (
identityGroupMembershipDAL
});
+ const folderService = secretFolderServiceFactory({
+ permissionService,
+ folderDAL,
+ folderVersionDAL,
+ projectEnvDAL,
+ snapshotService,
+ projectDAL,
+ folderCommitService,
+ secretApprovalPolicyService,
+ secretV2BridgeDAL,
+ dynamicSecretDAL,
+ secretRotationV2DAL,
+ honeyTokenDAL,
+ secretImportDAL,
+ secretService
+ });
+
const secretSharingService = secretSharingServiceFactory({
permissionService,
secretSharingDAL,
diff --git a/backend/src/server/routes/v2/secret-folder-router.ts b/backend/src/server/routes/v2/secret-folder-router.ts
index 12eb76122a..ffb8a3aa7a 100644
--- a/backend/src/server/routes/v2/secret-folder-router.ts
+++ b/backend/src/server/routes/v2/secret-folder-router.ts
@@ -441,4 +441,74 @@ export const registerSecretFolderRouter = async (server: FastifyZodProvider) =>
return { folder };
}
});
+
+ server.route({
+ method: "POST",
+ url: "/move",
+ config: {
+ rateLimit: secretsLimit
+ },
+ schema: {
+ hide: false,
+ operationId: "moveSecretFolder",
+ tags: [ApiDocsTags.Folders],
+ description: "Move a folder and its static-secret contents to a new path, optionally in a different environment",
+ security: [
+ {
+ bearerAuth: []
+ }
+ ],
+ body: z.object({
+ projectId: z.string().trim(),
+ folderId: z.string().trim().uuid(),
+ destinationEnvironment: z.string().trim(),
+ destinationPath: z.string().trim().default("/").transform(prefixWithSlash).transform(removeTrailingSlash),
+ shouldOverwrite: z.boolean().default(false)
+ }),
+ response: {
+ 200: z.object({
+ folderId: z.string(),
+ sourceEnvironment: z.string(),
+ sourcePath: z.string(),
+ destinationEnvironment: z.string(),
+ destinationPath: z.string(),
+ isFullyMoved: z.boolean(),
+ hasApprovalRequests: z.boolean()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const result = await server.services.folder.moveFolder({
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ projectId: req.body.projectId,
+ folderId: req.body.folderId,
+ destinationEnvironment: req.body.destinationEnvironment,
+ destinationPath: req.body.destinationPath,
+ shouldOverwrite: req.body.shouldOverwrite
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId: req.body.projectId,
+ event: {
+ type: EventType.MOVE_FOLDER,
+ metadata: {
+ folderId: result.folderId,
+ sourceEnvironment: result.sourceEnvironment,
+ sourcePath: result.sourcePath,
+ destinationEnvironment: result.destinationEnvironment,
+ destinationPath: result.destinationPath,
+ isFullyMoved: result.isFullyMoved,
+ hasApprovalRequests: result.hasApprovalRequests
+ }
+ }
+ });
+
+ return result;
+ }
+ });
};
diff --git a/backend/src/services/secret-folder/secret-folder-dal.ts b/backend/src/services/secret-folder/secret-folder-dal.ts
index a1c50f69be..031e39b157 100644
--- a/backend/src/services/secret-folder/secret-folder-dal.ts
+++ b/backend/src/services/secret-folder/secret-folder-dal.ts
@@ -526,6 +526,21 @@ export const secretFolderDALFactory = (db: TDbClient) => {
}
};
+ // acquires a row-level lock on the given folders so that concurrent secret inserts into them block
+ // until the surrounding transaction commits (the secret -> folder FK insert needs a conflicting FOR KEY SHARE lock).
+ const lockFoldersForUpdate = async (folderIds: string[], tx: Knex) => {
+ if (!folderIds.length) return [];
+ try {
+ const folders = await tx(TableName.SecretFolder)
+ .whereIn("id", folderIds)
+ .forUpdate()
+ .select(selectAllTableCols(TableName.SecretFolder));
+ return folders;
+ } catch (error) {
+ throw new DatabaseError({ error, name: "lockFoldersForUpdate" });
+ }
+ };
+
return {
...secretFolderOrm,
update,
@@ -540,6 +555,7 @@ export const secretFolderDALFactory = (db: TDbClient) => {
findByEnvsDeep,
findByParentId,
findByEnvId,
- findFoldersByRootAndIds
+ findFoldersByRootAndIds,
+ lockFoldersForUpdate
};
};
diff --git a/backend/src/services/secret-folder/secret-folder-service.ts b/backend/src/services/secret-folder/secret-folder-service.ts
index c5971d02e6..d2fbb17517 100644
--- a/backend/src/services/secret-folder/secret-folder-service.ts
+++ b/backend/src/services/secret-folder/secret-folder-service.ts
@@ -16,6 +16,7 @@ import { PgSqlLock } from "@app/keystore/keystore";
import { BadRequestError, NotFoundError } from "@app/lib/errors";
import { OrderByDirection, OrgServiceActor } from "@app/lib/types";
import { ActorType } from "@app/services/auth/auth-type";
+import { TSecretServiceFactory } from "@app/services/secret/secret-service";
import { SecretsOrderBy } from "@app/services/secret/secret-types";
import { buildFolderPath } from "@app/services/secret-folder/secret-folder-fns";
@@ -41,6 +42,8 @@ import {
TGetFolderByPathDTO,
TGetFolderDTO,
TGetFoldersDeepByEnvsDTO,
+ TMoveFolderDTO,
+ TMoveFolderResult,
TUpdateFolderDTO,
TUpdateManyFoldersDTO
} from "./secret-folder-types";
@@ -63,6 +66,7 @@ type TSecretFolderServiceFactoryDep = {
secretRotationV2DAL: Pick<TSecretRotationV2DALFactory, "existsByFolderIds">;
honeyTokenDAL: Pick<THoneyTokenDALFactory, "find">;
secretImportDAL: Pick<TSecretImportDALFactory, "findImportByFolderIds">;
+ secretService: Pick<TSecretServiceFactory, "moveSecrets">;
};
export type TSecretFolderServiceFactory = ReturnType<typeof secretFolderServiceFactory>;
@@ -80,7 +84,8 @@ export const secretFolderServiceFactory = ({
dynamicSecretDAL,
secretRotationV2DAL,
honeyTokenDAL,
- secretImportDAL
+ secretImportDAL,
+ secretService
}: TSecretFolderServiceFactoryDep) => {
const createFolder = async ({
projectId,
@@ -1459,6 +1464,35 @@ export const secretFolderServiceFactory = ({
return folder;
};
+ // shared subtree scan used by both the eligibility check and the move itself:
+ // a folder can only be moved if its entire recursive subtree contains nothing but plain static secrets.
+ const $getFolderMoveBlock = async (
+ subtree: { id: string; path: string }[],
+ fallbackPath: string,
+ tx: Knex
+ ): Promise<{ blockingType: TFolderMoveBlockingType; blockingPath: string } | null> => {
+ const folderIds = subtree.map((f) => f.id);
+ if (!folderIds.length) return null;
+
+ const pathByFolderId = new Map(subtree.map((f) => [f.id, f.path]));
+ const resolvePath = (folderId: string) => pathByFolderId.get(folderId) ?? fallbackPath;
+
+ // sequential early-exit checks, cheapest single-table queries first.
+ const importHit = await secretImportDAL.findImportByFolderIds(folderIds, tx);
+ if (importHit) return { blockingType: "secret_import", blockingPath: resolvePath(importHit.folderId) };
+
+ const [dynamicSecret] = await dynamicSecretDAL.find({ $in: { folderId: folderIds } }, { limit: 1, tx });
+ if (dynamicSecret) return { blockingType: "dynamic_secret", blockingPath: resolvePath(dynamicSecret.folderId) };
+
+ const [honeyToken] = await honeyTokenDAL.find({ $in: { folderId: folderIds } }, { limit: 1, tx });
+ if (honeyToken) return { blockingType: "honey_token", blockingPath: resolvePath(honeyToken.folderId) };
+
+ const rotation = await secretRotationV2DAL.existsByFolderIds(folderIds, tx);
+ if (rotation) return { blockingType: "secret_rotation", blockingPath: resolvePath(rotation.folderId) };
+
+ return null;
+ };
+
// checks whether a folder (and its entire recursive subtree) can be moved.
const getFolderMoveEligibility = async ({
actor,
@@ -1469,48 +1503,222 @@ export const secretFolderServiceFactory = ({
}: TGetFolderByIdDTO): Promise<TFolderMoveEligibility> => {
const folder = await getFolderById({ actor, actorId, actorOrgId, actorAuthMethod, id });
- const delay = (ms: number): Promise<void> => {
- return new Promise((resolve) => {
- setTimeout(resolve, ms);
- });
+ // run every read inside a transaction so it hits the primary database rather than a read replica
+ const block = await folderDAL.transaction(async (tx) => {
+ // parent folder + full recursive subtree (with paths); reserved folders are already excluded.
+ const subtree = await folderDAL.findByEnvsDeep({ parentIds: [folder.id] }, tx);
+ return $getFolderMoveBlock(subtree, folder.path, tx);
+ });
+
+ return {
+ canMove: !block,
+ folderName: folder.name,
+ blockingType: block?.blockingType,
+ blockingPath: block?.blockingPath
};
+ };
- await delay(10000);
+ // 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,
+ // move each folder's secrets via secretService.moveSecrets (which handles approval policies, snapshots and syncs),
+ // then delete the emptied source folders. folders left non-empty (e.g. secrets pending approval) are kept in place.
+ const moveFolder = async ({
+ projectId,
+ folderId,
+ destinationEnvironment,
+ destinationPath,
+ shouldOverwrite = false,
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId
+ }: TMoveFolderDTO): Promise<TMoveFolderResult> => {
+ // 1. resolve the source folder (getFolderById also runs the project-level permission check)
+ const sourceFolder = await getFolderById({ actor, actorId, actorOrgId, actorAuthMethod, id: folderId });
+ const sourceEnvironment = sourceFolder.environment.envSlug;
+ const sourceFolderPath = sourceFolder.path; // full path of the folder being moved, e.g. /a/b/target
+ const folderName = sourceFolder.name;
+ const sourceParentPath = path.dirname(sourceFolderPath); // /a/b ; for /target this is /
+
+ // 2. permission: a move is create-at-destination + delete-at-source (secret-level perms are enforced in moveSecrets)
+ const { permission } = await permissionService.getProjectPermission({
+ actor,
+ actorId,
+ projectId,
+ actorAuthMethod,
+ actorOrgId,
+ actionProjectType: ActionProjectType.SecretManager
+ });
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionActions.Create,
+ subject(ProjectPermissionSub.SecretFolders, { environment: destinationEnvironment, secretPath: destinationPath })
+ );
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionActions.Delete,
+ subject(ProjectPermissionSub.SecretFolders, { environment: sourceEnvironment, secretPath: sourceParentPath })
+ );
- // run every read inside a transaction so it hits the primary database rather than a read replica
- const block = await folderDAL.transaction(
- async (tx): Promise<{ blockingType: TFolderMoveBlockingType; blockingPath: string } | null> => {
- // parent folder + full recursive subtree (with paths); reserved folders are already excluded.
- const subtree = await folderDAL.findByEnvsDeep({ parentIds: [folder.id] }, tx);
- const folderIds = subtree.map((f) => f.id);
+ // 3. cyclic / no-op validation (only meaningful within the same environment)
+ if (destinationEnvironment === sourceEnvironment) {
+ if (destinationPath === sourceFolderPath || destinationPath.startsWith(`${sourceFolderPath}/`)) {
+ throw new BadRequestError({
+ message: "Cannot move a folder into itself or one of its own subfolders"
+ });
+ }
+ if (destinationPath === sourceParentPath) {
+ throw new BadRequestError({
+ message: `Folder '${folderName}' is already located at path '${destinationPath}'`
+ });
+ }
+ }
+
+ // 4. the destination parent must exist and must not already contain a folder of the same name
+ const destinationParentFolder = await folderDAL.findBySecretPath(
+ projectId,
+ destinationEnvironment,
+ destinationPath
+ );
+ if (!destinationParentFolder) {
+ throw new NotFoundError({
+ message: `Destination folder with path '${destinationPath}' in environment '${destinationEnvironment}' not found`
+ });
+ }
+ const finalDestinationPath = path.join(destinationPath, folderName);
+ const existingDestinationFolder = await folderDAL.findBySecretPath(
+ projectId,
+ destinationEnvironment,
+ finalDestinationPath
+ );
+ if (existingDestinationFolder) {
+ throw new BadRequestError({
+ message: `A folder named '${folderName}' already exists at path '${destinationPath}' in environment '${destinationEnvironment}'`
+ });
+ }
- if (!folderIds.length) return null;
+ const destinationFolderRoot = finalDestinationPath;
- const pathByFolderId = new Map(subtree.map((f) => [f.id, f.path]));
- const resolvePath = (folderId: string) => pathByFolderId.get(folderId) ?? folder.path;
+ // 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 subtree = await folderDAL.findByEnvsDeep({ parentIds: [sourceFolder.id] }, tx);
+ await folderDAL.lockFoldersForUpdate(
+ subtree.map((f) => f.id),
+ tx
+ );
- // sequential early-exit checks, cheapest single-table queries first.
- const importHit = await secretImportDAL.findImportByFolderIds(folderIds, tx);
- if (importHit) return { blockingType: "secret_import", blockingPath: resolvePath(importHit.folderId) };
+ const block = await $getFolderMoveBlock(subtree, sourceFolderPath, tx);
+ if (block) {
+ throw new BadRequestError({
+ message: `Cannot move folder '${folderName}'. It contains a ${block.blockingType.replace(
+ "_",
+ " "
+ )} at path '${block.blockingPath}'. Only folders that contain exclusively static secrets can be moved.`
+ });
+ }
- const [dynamicSecret] = await dynamicSecretDAL.find({ $in: { folderId: folderIds } }, { limit: 1, tx });
- if (dynamicSecret) return { blockingType: "dynamic_secret", blockingPath: resolvePath(dynamicSecret.folderId) };
+ const subtreeSecrets = await secretV2BridgeDAL.findByFolderIds({ folderIds: subtree.map((f) => f.id), tx });
+ const secretIdsByFolderId = new Map<string, string[]>();
+ for (const secret of subtreeSecrets) {
+ const list = secretIdsByFolderId.get(secret.folderId) ?? [];
+ list.push(secret.id);
+ secretIdsByFolderId.set(secret.folderId, list);
+ }
- const [honeyToken] = await honeyTokenDAL.find({ $in: { folderId: folderIds } }, { limit: 1, tx });
- if (honeyToken) return { blockingType: "honey_token", blockingPath: resolvePath(honeyToken.folderId) };
+ // build a move plan (root first). relativePath is relative to the folder being moved, where the folder itself is "/".
+ const planEntries = subtree
+ .slice()
+ .sort((a, b) => a.depth - b.depth)
+ .map((f) => {
+ const relativePath = f.path;
+ const sourceAbsPath = relativePath === "/" ? sourceFolderPath : `${sourceFolderPath}${relativePath}`;
+ const destinationAbsPath =
+ relativePath === "/" ? destinationFolderRoot : `${destinationFolderRoot}${relativePath}`;
+ return {
+ sourceFolderId: f.id,
+ name: f.name,
+ description: f.description,
+ depth: f.depth,
+ sourceAbsPath,
+ destinationAbsPath,
+ secretIds: secretIdsByFolderId.get(f.id) ?? []
+ };
+ });
+
+ return { plan: planEntries };
+ });
- const rotation = await secretRotationV2DAL.existsByFolderIds(folderIds, tx);
- if (rotation) return { blockingType: "secret_rotation", blockingPath: resolvePath(rotation.folderId) };
+ // 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),
+ name: entry.name,
+ description: entry.description
+ }))
+ });
- return null;
+ // 7. move secrets folder-by-folder, root first. moveSecrets handles approval policies, snapshots and syncs itself.
+ let hasApprovalRequests = false;
+ for (const entry of plan) {
+ if (!entry.secretIds.length) {
+ // eslint-disable-next-line no-continue
+ continue;
}
- );
+ const result = await secretService.moveSecrets({
+ projectId,
+ sourceEnvironment,
+ sourceSecretPath: entry.sourceAbsPath,
+ destinationEnvironment,
+ destinationSecretPath: entry.destinationAbsPath,
+ secretIds: entry.secretIds,
+ shouldOverwrite,
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId
+ });
+ // a missing direct update on either side means moveSecrets routed the change through an approval request
+ if (!result.isDestinationUpdated || !result.isSourceUpdated) {
+ hasApprovalRequests = true;
+ }
+ }
+
+ // 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 }]
+ });
+ }
+
+ await secretV2BridgeDAL.invalidateSecretCacheByProjectId(projectId);
return {
- canMove: !block,
- folderName: folder.name,
- blockingType: block?.blockingType,
- blockingPath: block?.blockingPath
+ folderId,
+ sourceEnvironment,
+ sourcePath: sourceFolderPath,
+ destinationEnvironment,
+ destinationPath,
+ isFullyMoved,
+ hasApprovalRequests
};
};
@@ -1522,6 +1730,7 @@ export const secretFolderServiceFactory = ({
getFolders,
getFolderById,
getFolderMoveEligibility,
+ moveFolder,
getFolderByPath,
getProjectFolderCount,
getFoldersMultiEnv,
diff --git a/backend/src/services/secret-folder/secret-folder-types.ts b/backend/src/services/secret-folder/secret-folder-types.ts
index 6d1e8ce6cb..70b4798532 100644
--- a/backend/src/services/secret-folder/secret-folder-types.ts
+++ b/backend/src/services/secret-folder/secret-folder-types.ts
@@ -65,6 +65,25 @@ export type TFolderMoveEligibility = {
blockingPath?: string;
};
+export type TMoveFolderDTO = {
+ folderId: string;
+ destinationEnvironment: string;
+ destinationPath: string;
+ shouldOverwrite?: boolean;
+} & TProjectPermission;
+
+export type TMoveFolderResult = {
+ folderId: string;
+ sourceEnvironment: string;
+ 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 move
+ hasApprovalRequests: boolean;
+};
+
export type TGetFoldersDeepByEnvsDTO = {
projectId: string;
environments: string[];
diff --git a/frontend/src/hooks/api/secretFolders/index.tsx b/frontend/src/hooks/api/secretFolders/index.tsx
index 9d2e446215..4a30e55f93 100644
--- a/frontend/src/hooks/api/secretFolders/index.tsx
+++ b/frontend/src/hooks/api/secretFolders/index.tsx
@@ -4,5 +4,6 @@ export {
useGetFoldersByEnv,
useGetOrCreateFolder,
useGetProjectFolders,
+ useMoveFolder,
useUpdateFolder
} from "./queries";
diff --git a/frontend/src/hooks/api/secretFolders/queries.tsx b/frontend/src/hooks/api/secretFolders/queries.tsx
index 56f7825c07..ed0dc73f47 100644
--- a/frontend/src/hooks/api/secretFolders/queries.tsx
+++ b/frontend/src/hooks/api/secretFolders/queries.tsx
@@ -11,12 +11,15 @@ import { apiRequest } from "@app/config/request";
import { dashboardKeys } from "@app/hooks/api/dashboard/queries";
import { commitKeys } from "../folderCommits/queries";
+import { secretApprovalRequestKeys } from "../secretApprovalRequest/queries";
import { secretSnapshotKeys } from "../secretSnapshots/queries";
import {
TCreateFolderDTO,
TDeleteFolderDTO,
TGetFoldersByEnvDTO,
TGetProjectFoldersDTO,
+ TMoveFolderDTO,
+ TMoveFolderResponse,
TProjectEnvironmentsFolders,
TSecretFolder,
TUpdateFolderBatchDTO,
@@ -370,3 +373,65 @@ export const useUpdateFolderBatch = () => {
}
});
};
+
+export const useMoveFolder = () => {
+ const queryClient = useQueryClient();
+
+ return useMutation<TMoveFolderResponse, object, TMoveFolderDTO>({
+ mutationFn: async ({
+ projectId,
+ folderId,
+ destinationEnvironment,
+ destinationPath,
+ shouldOverwrite = false
+ }) => {
+ const { data } = await apiRequest.post<TMoveFolderResponse>("/api/v2/folders/move", {
+ projectId,
+ folderId,
+ destinationEnvironment,
+ destinationPath,
+ shouldOverwrite
+ });
+ return data;
+ },
+ onSuccess: (
+ _,
+ { projectId, sourceEnvironment, sourcePath, destinationEnvironment, destinationPath }
+ ) => {
+ const invalidatePath = (environment: string, path: string) => {
+ queryClient.invalidateQueries({
+ queryKey: dashboardKeys.getDashboardSecrets({ projectId, secretPath: path })
+ });
+ queryClient.invalidateQueries({
+ queryKey: folderQueryKeys.getSecretFolders({ projectId, environment, path })
+ });
+ queryClient.invalidateQueries({
+ queryKey: secretSnapshotKeys.list({ projectId, environment, directory: path })
+ });
+ queryClient.invalidateQueries({
+ queryKey: secretSnapshotKeys.count({ projectId, environment, directory: path })
+ });
+ queryClient.invalidateQueries({
+ queryKey: commitKeys.count({ projectId, environment, directory: path })
+ });
+ queryClient.invalidateQueries({
+ queryKey: commitKeys.history({ projectId, environment, directory: path })
+ });
+ };
+
+ // the folder's old parent listing and its new parent listing both change
+ invalidatePath(sourceEnvironment, sourcePath);
+ invalidatePath(destinationEnvironment, destinationPath);
+
+ queryClient.invalidateQueries({
+ queryKey: folderQueryKeys.getProjectEnvironmentsFolders(projectId)
+ });
+ queryClient.invalidateQueries({
+ queryKey: secretApprovalRequestKeys.count({ projectId })
+ });
+ queryClient.invalidateQueries({
+ queryKey: secretApprovalRequestKeys.listAllForProject({ projectId })
+ });
+ }
+ });
+};
diff --git a/frontend/src/hooks/api/secretFolders/types.ts b/frontend/src/hooks/api/secretFolders/types.ts
index f3e3cecaf6..ef063b3a5a 100644
--- a/frontend/src/hooks/api/secretFolders/types.ts
+++ b/frontend/src/hooks/api/secretFolders/types.ts
@@ -72,3 +72,24 @@ export type TUpdateFolderBatchDTO = {
description?: string | null;
}[];
};
+
+export type TMoveFolderDTO = {
+ projectId: string;
+ folderId: string;
+ // source environment + parent path of the folder being moved; used only for cache invalidation
+ sourceEnvironment: string;
+ sourcePath: string;
+ destinationEnvironment: string;
+ destinationPath: string;
+ shouldOverwrite?: boolean;
+};
+
+export type TMoveFolderResponse = {
+ folderId: string;
+ sourceEnvironment: string;
+ sourcePath: string;
+ destinationEnvironment: string;
+ destinationPath: string;
+ isFullyMoved: boolean;
+ hasApprovalRequests: boolean;
+};
diff --git a/frontend/src/pages/secret-manager/OverviewPage/components/SelectionPanel/SelectionPanel.tsx b/frontend/src/pages/secret-manager/OverviewPage/components/SelectionPanel/SelectionPanel.tsx
index cc94d36d79..4365018bd7 100644
--- a/frontend/src/pages/secret-manager/OverviewPage/components/SelectionPanel/SelectionPanel.tsx
+++ b/frontend/src/pages/secret-manager/OverviewPage/components/SelectionPanel/SelectionPanel.tsx
@@ -521,6 +521,7 @@ export const SelectionPanel = ({
sourceSecretPath={secretPath}
secrets={selectedEntries[EntryType.SECRET]}
rotations={selectedEntries[EntryType.SECRET_ROTATION]}
+ folders={selectedEntries[EntryType.FOLDER]}
onComplete={resetSelectedEntries}
/>
<BulkTagDialog
diff --git a/frontend/src/pages/secret-manager/OverviewPage/components/SelectionPanel/components/MoveSecretsDialog/MoveSecretsDialog.tsx b/frontend/src/pages/secret-manager/OverviewPage/components/SelectionPanel/components/MoveSecretsDialog/MoveSecretsDialog.tsx
index 2e25930bd4..323917ae90 100644
--- a/frontend/src/pages/secret-manager/OverviewPage/components/SelectionPanel/components/MoveSecretsDialog/MoveSecretsDialog.tsx
+++ b/frontend/src/pages/secret-manager/OverviewPage/components/SelectionPanel/components/MoveSecretsDialog/MoveSecretsDialog.tsx
@@ -42,6 +42,8 @@ import { useDebounce } from "@app/hooks";
import { useMoveSecrets } from "@app/hooks/api";
import { useGetProjectSecretsQuickSearch } from "@app/hooks/api/dashboard";
import { ProjectEnv } from "@app/hooks/api/projects/types";
+import { useMoveFolder } from "@app/hooks/api/secretFolders";
+import { TSecretFolder } from "@app/hooks/api/secretFolders/types";
import { TSecretRotationV2, useMoveSecretRotation } from "@app/hooks/api/secretRotationsV2";
import { SecretV3RawSanitized } from "@app/hooks/api/secrets/types";
@@ -55,6 +57,7 @@ type Props = {
sourceSecretPath: string;
secrets: Record<string, Record<string, SecretV3RawSanitized>>;
rotations: Record<string, Record<string, TSecretRotationV2>>;
+ folders: Record<string, Record<string, TSecretFolder>>;
onComplete: () => void;
};
@@ -129,6 +132,29 @@ type MoveResults = {
message: string;
}[];
+// the modal moves secrets, rotations and folders together, so the copy reflects what is actually selected
+const getMoveSelectionCopy = ({
+ secrets,
+ rotations,
+ folders
+}: {
+ secrets: Record<string, unknown>;
+ rotations: Record<string, unknown>;
+ folders: Record<string, unknown>;
+}) => {
+ const hasFolders = Object.keys(folders).length > 0;
+ const hasSecretsOrRotations =
+ Object.keys(secrets).length > 0 || Object.keys(rotations).length > 0;
+
+ if (hasFolders && !hasSecretsOrRotations) {
+ return { title: "Move Folders", action: "Move Folders", noun: "folders" };
+ }
+ if (hasFolders && hasSecretsOrRotations) {
+ return { title: "Move Items", action: "Move Items", noun: "items" };
+ }
+ return { title: "Move Secrets", action: "Move Secrets", noun: "secrets" };
+};
+
const singleEnvFormSchema = z.object({
environment: z.string().trim(),
shouldOverwrite: z.boolean().default(false)
@@ -192,6 +218,7 @@ const SingleEnvContent = ({
onClose,
secrets,
rotations,
+ folders,
environments,
visibleEnvs,
projectId,
@@ -199,8 +226,11 @@ const SingleEnvContent = ({
sourceSecretPath
}: ContentProps) => {
const sourceEnv = visibleEnvs[0];
+ const moveCopy = getMoveSelectionCopy({ secrets, rotations, folders });
+ const showOverwriteOption = Object.keys(secrets).length > 0 || Object.keys(rotations).length > 0;
const moveSecrets = useMoveSecrets();
const moveSecretRotation = useMoveSecretRotation();
+ const moveFolder = useMoveFolder();
const [selectedPath, setSelectedPath] = useState<OptionValue | null>({
secretPath: "/"
});
@@ -248,10 +278,14 @@ const SingleEnvContent = ({
.map((rotationRecord) => rotationRecord[sourceEnv.slug])
.filter((rotation): rotation is TSecretRotationV2 => Boolean(rotation));
- if (!secretsToMove.length && !rotationsToMove.length) {
+ const foldersToMove = Object.values(folders)
+ .map((folderRecord) => folderRecord[sourceEnv.slug])
+ .filter((folder): folder is TSecretFolder => Boolean(folder));
+
+ if (!secretsToMove.length && !rotationsToMove.length && !foldersToMove.length) {
createNotification({
type: "info",
- text: "No secrets or rotations to move in this environment"
+ text: "Nothing selected to move in this environment"
});
return;
}
@@ -300,6 +334,34 @@ const SingleEnvContent = ({
}
}
+ const folderFailures: { name: string; message: string }[] = [];
+ let folderSuccessCount = 0;
+ let folderApprovalCount = 0;
+
+ // eslint-disable-next-line no-restricted-syntax
+ for await (const folder of foldersToMove) {
+ try {
+ const result = await moveFolder.mutateAsync({
+ projectId,
+ folderId: folder.id,
+ sourceEnvironment: sourceEnv.slug,
+ sourcePath: sourceSecretPath,
+ destinationEnvironment: data.environment,
+ destinationPath: selectedPath.secretPath,
+ shouldOverwrite: data.shouldOverwrite
+ });
+ folderSuccessCount += 1;
+ if (result.hasApprovalRequests) folderApprovalCount += 1;
+ } catch (error) {
+ let message = (error as Error)?.message ?? "Failed to move folder";
+ if (axios.isAxiosError(error)) {
+ const responseMessage = (error?.response?.data as { message?: string })?.message;
+ if (responseMessage) message = responseMessage;
+ }
+ folderFailures.push({ name: folder.name, message });
+ }
+ }
+
if (secretsToMove.length) {
if (isDestinationUpdated && isSourceUpdated) {
createNotification({
@@ -333,6 +395,27 @@ const SingleEnvContent = ({
});
}
+ if (folderSuccessCount > 0) {
+ createNotification({
+ type: folderApprovalCount > 0 ? "info" : "success",
+ text:
+ folderApprovalCount > 0
+ ? `Moved ${folderSuccessCount} folder${
+ folderSuccessCount === 1 ? "" : "s"
+ }. Approval requests were generated for change-policy protected paths.`
+ : `Successfully moved ${folderSuccessCount} folder${folderSuccessCount === 1 ? "" : "s"}`
+ });
+ }
+
+ if (folderFailures.length > 0) {
+ createNotification({
+ type: "error",
+ text: `Failed to move ${folderFailures.length} folder${
+ folderFailures.length === 1 ? "" : "s"
+ }: ${folderFailures.map((f) => f.name).join(", ")}`
+ });
+ }
+
onClose();
onComplete();
};
@@ -381,31 +464,33 @@ const SingleEnvContent = ({
</FieldDescription>
</FieldContent>
</Field>
- <Controller
- control={control}
- name="shouldOverwrite"
- render={({ field: { onBlur, value, onChange } }) => (
- <Field className="mt-4">
- <Field orientation="horizontal">
- <Checkbox
- id="overwrite-checkbox"
- isChecked={value}
- onCheckedChange={onChange}
- onBlur={onBlur}
- variant="project"
- />
- <FieldLabel htmlFor="overwrite-checkbox" className="cursor-pointer">
- Overwrite existing secrets
- </FieldLabel>
+ {showOverwriteOption && (
+ <Controller
+ control={control}
+ name="shouldOverwrite"
+ render={({ field: { onBlur, value, onChange } }) => (
+ <Field className="mt-4">
+ <Field orientation="horizontal">
+ <Checkbox
+ id="overwrite-checkbox"
+ isChecked={value}
+ onCheckedChange={onChange}
+ onBlur={onBlur}
+ variant="project"
+ />
+ <FieldLabel htmlFor="overwrite-checkbox" className="cursor-pointer">
+ Overwrite existing secrets
+ </FieldLabel>
+ </Field>
+ <FieldDescription>
+ {value
+ ? "Secrets with conflicting keys at the destination will be overwritten"
+ : "Secrets with conflicting keys at the destination will not be overwritten"}
+ </FieldDescription>
</Field>
- <FieldDescription>
- {value
- ? "Secrets with conflicting keys at the destination will be overwritten"
- : "Secrets with conflicting keys at the destination will not be overwritten"}
- </FieldDescription>
- </Field>
- )}
- />
+ )}
+ />
+ )}
<DialogFooter className="mt-6">
<DialogClose asChild>
<Button variant="outline" onClick={onClose}>
@@ -418,7 +503,7 @@ const SingleEnvContent = ({
isDisabled={!destinationSelected || isSubmitting}
isPending={isSubmitting}
>
- Move Secrets
+ {moveCopy.action}
</Button>
</DialogFooter>
</form>
@@ -436,6 +521,7 @@ const MultiEnvContent = ({
onClose,
secrets,
rotations,
+ folders,
environments,
projectId,
projectSlug,
@@ -443,6 +529,9 @@ const MultiEnvContent = ({
}: ContentProps) => {
const moveSecrets = useMoveSecrets();
const moveSecretRotation = useMoveSecretRotation();
+ const moveFolder = useMoveFolder();
+ const moveCopy = getMoveSelectionCopy({ secrets, rotations, folders });
+ const showOverwriteOption = Object.keys(secrets).length > 0 || Object.keys(rotations).length > 0;
const { permission } = useProjectPermission();
const [moveResults, setMoveResults] = useState<MoveResults | null>(null);
const [selectedPath, setSelectedPath] = useState<OptionValue | null>({
@@ -550,13 +639,25 @@ const MultiEnvContent = ({
})
);
+ const foldersByEnv: Record<string, TSecretFolder[]> = Object.fromEntries(
+ environments.map((env) => [env.slug, []])
+ );
+
+ Object.values(folders).forEach((folderRecord) =>
+ Object.entries(folderRecord).forEach(([env, folder]) => {
+ if (foldersByEnv[env]) foldersByEnv[env].push(folder);
+ })
+ );
+
// eslint-disable-next-line no-restricted-syntax
for await (const environment of environments) {
const envSlug = environment.slug;
const { cannotMoveSecrets, cannotMoveRotations } = moveEligibility[envSlug];
- if (cannotMoveSecrets && cannotMoveRotations) {
+ const foldersToMove = foldersByEnv[envSlug];
+
+ if (cannotMoveSecrets && cannotMoveRotations && !foldersToMove.length) {
// eslint-disable-next-line no-continue
continue;
}
@@ -564,10 +665,10 @@ const MultiEnvContent = ({
const secretsToMove = cannotMoveSecrets ? [] : secretsByEnv[envSlug];
const rotationsToMove = cannotMoveRotations ? [] : rotationsByEnv[envSlug];
- if (!secretsToMove.length && !rotationsToMove.length) {
+ if (!secretsToMove.length && !rotationsToMove.length && !foldersToMove.length) {
results.push({
name: environment.name,
- message: "No secrets or rotations selected in environment",
+ message: "Nothing selected in environment",
status: MoveResult.Info,
id: environment.id
});
@@ -660,6 +761,43 @@ const MultiEnvContent = ({
});
}
}
+
+ // eslint-disable-next-line no-restricted-syntax
+ for await (const folder of foldersToMove) {
+ try {
+ const { hasApprovalRequests } = await moveFolder.mutateAsync({
+ projectId,
+ folderId: folder.id,
+ sourceEnvironment: environment.slug,
+ sourcePath: sourceSecretPath,
+ destinationEnvironment: environment.slug,
+ destinationPath: selectedPath.secretPath,
+ shouldOverwrite: data.shouldOverwrite
+ });
+
+ results.push({
+ name: `${environment.name} / ${folder.name}`,
+ message: hasApprovalRequests
+ ? "Folder moved. Approval requests were generated for change-policy protected paths."
+ : "Successfully moved folder",
+ status: hasApprovalRequests ? MoveResult.Info : MoveResult.Success,
+ id: `${environment.id}-folder-${folder.id}`
+ });
+ } catch (error) {
+ let errorMessage = (error as Error)?.message ?? "Failed to move folder";
+ if (axios.isAxiosError(error)) {
+ const responseMessage = (error?.response?.data as { message?: string })?.message;
+ if (responseMessage) errorMessage = responseMessage;
+ }
+
+ results.push({
+ name: `${environment.name} / ${folder.name}`,
+ message: errorMessage,
+ status: MoveResult.Error,
+ id: `${environment.id}-folder-${folder.id}`
+ });
+ }
+ }
}
setMoveResults(results);
@@ -675,11 +813,11 @@ const MultiEnvContent = ({
return <MoveResultsView moveResults={moveResults} onComplete={onComplete} />;
}
- if (moveSecrets.isPending || moveSecretRotation.isPending) {
+ if (moveSecrets.isPending || moveSecretRotation.isPending || moveFolder.isPending) {
return (
<div className="flex h-full flex-col items-center justify-center py-2.5">
<LoaderCircleIcon className="size-8 animate-spin text-accent" />
- <p className="mt-4 text-sm text-accent">Moving secrets...</p>
+ <p className="mt-4 text-sm text-accent">Moving {moveCopy.noun}...</p>
</div>
);
}
@@ -688,7 +826,9 @@ const MultiEnvContent = ({
<form onSubmit={handleSubmit(handleFormSubmit)}>
<Alert variant="info" className="mb-4">
<InfoIcon />
- <AlertTitle>Select a single environment to move secrets across environments.</AlertTitle>
+ <AlertTitle>
+ Select a single environment to move {moveCopy.noun} across environments.
+ </AlertTitle>
</Alert>
<Field>
<FieldLabel>Secret Path</FieldLabel>
@@ -717,31 +857,33 @@ const MultiEnvContent = ({
</AlertDescription>
</Alert>
)}
- <Controller
- control={control}
- name="shouldOverwrite"
- render={({ field: { onBlur, value, onChange } }) => (
- <Field className="mt-4">
- <Field orientation="horizontal">
- <Checkbox
- id="overwrite-checkbox-multi"
- isChecked={value}
- onCheckedChange={onChange}
- onBlur={onBlur}
- variant="project"
- />
- <FieldLabel htmlFor="overwrite-checkbox-multi" className="cursor-pointer">
- Overwrite existing secrets
- </FieldLabel>
+ {showOverwriteOption && (
+ <Controller
+ control={control}
+ name="shouldOverwrite"
+ render={({ field: { onBlur, value, onChange } }) => (
+ <Field className="mt-4">
+ <Field orientation="horizontal">
+ <Checkbox
+ id="overwrite-checkbox-multi"
+ isChecked={value}
+ onCheckedChange={onChange}
+ onBlur={onBlur}
+ variant="project"
+ />
+ <FieldLabel htmlFor="overwrite-checkbox-multi" className="cursor-pointer">
+ Overwrite existing secrets
+ </FieldLabel>
+ </Field>
+ <FieldDescription>
+ {value
+ ? "Secrets with conflicting keys at the destination will be overwritten"
+ : "Secrets with conflicting keys at the destination will not be overwritten"}
+ </FieldDescription>
</Field>
- <FieldDescription>
- {value
- ? "Secrets with conflicting keys at the destination will be overwritten"
- : "Secrets with conflicting keys at the destination will not be overwritten"}
- </FieldDescription>
- </Field>
- )}
- />
+ )}
+ />
+ )}
<DialogFooter className="mt-6">
<DialogClose asChild>
<Button variant="outline" onClick={onClose}>
@@ -754,7 +896,7 @@ const MultiEnvContent = ({
isDisabled={!destinationSelected || isSubmitting}
isPending={isSubmitting}
>
- Move Secrets
+ {moveCopy.action}
</Button>
</DialogFooter>
</form>
@@ -763,6 +905,7 @@ const MultiEnvContent = ({
export const MoveSecretsModal = ({ isOpen, onOpenChange, visibleEnvs, ...props }: Props) => {
const isSingleEnvMode = visibleEnvs.length === 1;
+ const moveCopy = getMoveSelectionCopy(props);
return (
<Dialog
@@ -774,11 +917,11 @@ export const MoveSecretsModal = ({ isOpen, onOpenChange, visibleEnvs, ...props }
>
<DialogContent className="max-w-xl overflow-visible [&>*]:min-w-0">
<DialogHeader>
- <DialogTitle>Move Secrets</DialogTitle>
+ <DialogTitle>{moveCopy.title}</DialogTitle>
<DialogDescription>
{isSingleEnvMode
- ? "Move the selected secrets to a new environment and folder location"
- : "Move the selected secrets across all environments to a new folder location"}
+ ? `Move the selected ${moveCopy.noun} to a new environment and folder location`
+ : `Move the selected ${moveCopy.noun} across all environments to a new folder location`}
</DialogDescription>
</DialogHeader>
{isSingleEnvMode ? (