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
fix(secret-sync): check move warnings against the destination root
Calvin404e52a0d759
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.tsindex a3a2f2b4ac..358832fee8 100644--- a/backend/src/lib/api-docs/constants.ts+++ b/backend/src/lib/api-docs/constants.ts@@ -1509,13 +1509,13 @@ export const DASHBOARD = {MOVE_WARNINGS: {projectId: "The ID of the project containing the items being moved or copied.",sourceEnvironment: "The slug of the environment the items are moved or copied from.",- sourceSecretPath:- "The path the items live at now. For secrets, the folder holding them. For a folder, the folder's own path.",+ sourceSecretPath: "The folder the items are moved or copied from.",destinationEnvironment: "The slug of the environment the items are moved or copied to.",- destinationSecretPath:- "The path the items will live at. For secrets, the destination folder. For a folder, the destination folder followed by the moved folder's name.",+ destinationSecretPath: "The folder the items are moved or copied into.",secretSyncs:- "The secret syncs that cover the destination path but not the source path, so would start sending the items to their destination. Details of a sync you cannot read are null.",+ "The secret syncs you can read that cover the destination folder or a folder beneath it, but not the source folder, so may start sending the items to their destination.",+ hasHiddenSecretSyncs:+ "Whether secret syncs you cannot read would also start sending the items to their destination.",syncId: "The ID of the secret sync.",syncName: "The name of the secret sync.",syncDestination: "The external service the secret sync sends secrets to.",diff --git a/backend/src/server/routes/v1/dashboard-router.ts b/backend/src/server/routes/v1/dashboard-router.tsindex 87409831d8..5676ccef38 100644--- a/backend/src/server/routes/v1/dashboard-router.ts+++ b/backend/src/server/routes/v1/dashboard-router.ts@@ -12,6 +12,7 @@ import { BadRequestError, NotFoundError } from "@app/lib/errors";import { prefixWithSlash, removeTrailingSlash } from "@app/lib/fn";import { OrderByDirection } from "@app/lib/types";import { readLimit, secretsLimit } from "@app/server/config/rateLimiter";+import { slugSchema } from "@app/server/lib/schemas";import { getTelemetryDistinctId } from "@app/server/lib/telemetry";import { getUserAgentType } from "@app/server/plugins/audit-log";import { verifyAuth } from "@app/server/plugins/auth/verify-auth";@@ -2187,8 +2188,10 @@ export const registerDashboardRouter = async (server: FastifyZodProvider) => {}],querystring: z.object({- projectId: z.string().trim().min(1).max(64).describe(DASHBOARD.MOVE_WARNINGS.projectId),- sourceEnvironment: z.string().trim().min(1).max(64).describe(DASHBOARD.MOVE_WARNINGS.sourceEnvironment),+ projectId: z.string().trim().uuid().describe(DASHBOARD.MOVE_WARNINGS.projectId),+ sourceEnvironment: slugSchema({ field: "Source environment" }).describe(+ DASHBOARD.MOVE_WARNINGS.sourceEnvironment+ ),sourceSecretPath: z.string().trim()@@ -2197,12 +2200,9 @@ export const registerDashboardRouter = async (server: FastifyZodProvider) => {.transform(prefixWithSlash).transform(removeTrailingSlash).describe(DASHBOARD.MOVE_WARNINGS.sourceSecretPath),- destinationEnvironment: z- .string()- .trim()- .min(1)- .max(64)- .describe(DASHBOARD.MOVE_WARNINGS.destinationEnvironment),+ destinationEnvironment: slugSchema({ field: "Destination environment" }).describe(+ DASHBOARD.MOVE_WARNINGS.destinationEnvironment+ ),destinationSecretPath: z.string().trim()@@ -2216,23 +2216,22 @@ export const registerDashboardRouter = async (server: FastifyZodProvider) => {200: z.object({secretSyncs: z.object({- id: z.string().nullable().describe(DASHBOARD.MOVE_WARNINGS.syncId),- name: z.string().nullable().describe(DASHBOARD.MOVE_WARNINGS.syncName),- destination: z.nativeEnum(SecretSync).nullable().describe(DASHBOARD.MOVE_WARNINGS.syncDestination),+ id: z.string().describe(DASHBOARD.MOVE_WARNINGS.syncId),+ name: z.string().describe(DASHBOARD.MOVE_WARNINGS.syncName),+ destination: z.nativeEnum(SecretSync).describe(DASHBOARD.MOVE_WARNINGS.syncDestination),secretPath: z.string().nullable().describe(DASHBOARD.MOVE_WARNINGS.syncSecretPath),- includeAllSubFolders: z.boolean().nullable().describe(DASHBOARD.MOVE_WARNINGS.includeAllSubFolders),- isAutoSyncEnabled: z.boolean().nullable().describe(DASHBOARD.MOVE_WARNINGS.isAutoSyncEnabled)+ includeAllSubFolders: z.boolean().describe(DASHBOARD.MOVE_WARNINGS.includeAllSubFolders),+ isAutoSyncEnabled: z.boolean().describe(DASHBOARD.MOVE_WARNINGS.isAutoSyncEnabled)}).array()- .describe(DASHBOARD.MOVE_WARNINGS.secretSyncs)+ .describe(DASHBOARD.MOVE_WARNINGS.secretSyncs),+ hasHiddenSecretSyncs: z.boolean().describe(DASHBOARD.MOVE_WARNINGS.hasHiddenSecretSyncs)})}},onRequest: verifyAuth([AuthMode.JWT, AuthMode.OAUTH]),handler: async (req) => {- const secretSyncs = await server.services.secretSync.listSecretSyncsNewlyCoveringPath(req.query, req.permission);-- return { secretSyncs };+ return server.services.secretSync.listSecretSyncsNewlyCoveringPath(req.query, req.permission);}});diff --git a/backend/src/services/secret-sync/secret-sync-queue.ts b/backend/src/services/secret-sync/secret-sync-queue.tsindex f79a415646..d1234b5560 100644--- a/backend/src/services/secret-sync/secret-sync-queue.ts+++ b/backend/src/services/secret-sync/secret-sync-queue.ts@@ -44,7 +44,7 @@ import {import { SecretSyncError } from "@app/services/secret-sync/secret-sync-errors";import { enterpriseSyncCheck, parseSyncErrorMessage, SecretSyncFns } from "@app/services/secret-sync/secret-sync-fns";import { SECRET_SYNC_DAILY_RETRY_DESTINATIONS, SECRET_SYNC_NAME_MAP } from "@app/services/secret-sync/secret-sync-maps";-import { buildSyncPayload, findSecretSyncsCoveringPath } from "@app/services/secret-sync/secret-sync-recursive-fns";+import { buildSyncPayload, isPathCoveredBySecretSync } from "@app/services/secret-sync/secret-sync-recursive-fns";import {SecretSyncAction,SecretSyncStatus,@@ -1052,12 +1052,9 @@ export const secretSyncQueueFactory = ({const environment = await projectEnvDAL.findOne({ projectId, slug: environmentSlug });if (!environment) return;- const secretSyncs = (- await findSecretSyncsCoveringPath(- { projectId, environment: { id: environment.id, slug: environmentSlug }, secretPath },- { folderDAL, secretSyncDAL }- )- ).filter((sync) => sync.isAutoSyncEnabled);+ const secretSyncs = (await secretSyncDAL.find({ projectId, isAutoSyncEnabled: true })).filter((sync) =>+ isPathCoveredBySecretSync(sync, { envId: environment.id, secretPath })+ );await secretSyncDAL.update({diff --git a/backend/src/services/secret-sync/secret-sync-recursive-fns.test.ts b/backend/src/services/secret-sync/secret-sync-recursive-fns.test.tsindex 9436dd1aa3..7f5d4e3e06 100644--- a/backend/src/services/secret-sync/secret-sync-recursive-fns.test.ts+++ b/backend/src/services/secret-sync/secret-sync-recursive-fns.test.ts@@ -1,8 +1,8 @@import {buildSyncPayload,- findSecretSyncsCoveringPath,- getAncestorPaths,getSyncedFolders,+ isPathCoveredBySecretSync,+ isPathOrDescendantCoveredBySecretSync,mergeImportedSecrets,toSyncsNewlyCoveringPath} from "./secret-sync-recursive-fns";@@ -45,133 +45,80 @@ describe("getSyncedFolders", () => {});});-describe("getAncestorPaths", () => {- test("returns the root for a top-level path", () => {- expect(getAncestorPaths("/")).toEqual([]);+describe("isPathCoveredBySecretSync", () => {+ const sync = (path: string, includeAllSubFolders?: boolean, envId = "env-1") => ({+ environment: { id: envId },+ folder: { path },+ syncOptions: includeAllSubFolders === undefined ? {} : { includeAllSubFolders }});- test("returns every ancestor, closest last", () => {- expect(getAncestorPaths("/backend/api/v2")).toEqual(["/", "/backend", "/backend/api"]);- });+ const covers = (entry: ReturnType<typeof sync>, secretPath: string, envId = "env-1") =>+ isPathCoveredBySecretSync(entry, { envId, secretPath });- test("never includes the path itself", () => {- for (const path of ["/", "/backend", "/backend/api", "/backend/api/v2"]) {- expect(getAncestorPaths(path)).not.toContain(path);- }+ test("covers its own path whether or not it includes subfolders", () => {+ expect(covers(sync("/apps", false), "/apps")).toBe(true);+ expect(covers(sync("/apps", true), "/apps")).toBe(true);+ expect(covers(sync("/apps"), "/apps")).toBe(true);});- test("returns one fewer entry than the path has segments", () => {- expect(getAncestorPaths("/a")).toHaveLength(1);- expect(getAncestorPaths("/a/b")).toHaveLength(2);- expect(getAncestorPaths("/a/b/c")).toHaveLength(3);- expect(getAncestorPaths("/a/b/c/d")).toHaveLength(4);+ test("covers a descendant path only when it includes subfolders", () => {+ expect(covers(sync("/apps", true), "/apps/payments/new")).toBe(true);+ expect(covers(sync("/apps", false), "/apps/payments")).toBe(false);+ expect(covers(sync("/apps"), "/apps/payments")).toBe(false);});- test("treats a trailing slash as the same path", () => {- expect(getAncestorPaths("/backend/api/")).toEqual(getAncestorPaths("/backend/api"));+ test("covers everything from the root when it includes subfolders", () => {+ expect(covers(sync("/", true), "/apps/payments")).toBe(true);+ expect(covers(sync("/", false), "/apps")).toBe(false);+ expect(covers(sync("/", false), "/")).toBe(true);});- test("tolerates repeated separators", () => {- expect(getAncestorPaths("/backend//api")).toEqual(getAncestorPaths("/backend/api"));+ test("never covers an ancestor or a sibling sharing a name prefix", () => {+ expect(covers(sync("/apps/payments", true), "/apps")).toBe(false);+ expect(covers(sync("/apps", true), "/apps-legacy")).toBe(false);});- test("returns an empty list for inputs that name no folder", () => {- // The queue passes whatever path the write carried. An empty result must mean- // "no ancestors to consider", never a lookup for a folder that cannot exist.- expect(getAncestorPaths("")).toEqual([]);- expect(getAncestorPaths("//")).toEqual([]);+ test("never covers a path in another environment", () => {+ expect(covers(sync("/apps", true, "env-2"), "/apps")).toBe(false);});- test("every returned path is absolute and free of a trailing slash", () => {- for (const ancestor of getAncestorPaths("/a/b/c/d")) {- expect(ancestor.startsWith("/")).toBe(true);- if (ancestor !== "/") expect(ancestor.endsWith("/")).toBe(false);- }- });-- test("returns the root exactly once, and only as the first entry", () => {- const ancestors = getAncestorPaths("/a/b/c");- expect(ancestors.filter((entry) => entry === "/")).toHaveLength(1);- expect(ancestors[0]).toBe("/");+ test("never covers anything without a folder", () => {+ expect(+ isPathCoveredBySecretSync({ environment: { id: "env-1" }, folder: null }, { envId: "env-1", secretPath: "/" })+ ).toBe(false);});- test("returns the root for a single-segment path", () => {- expect(getAncestorPaths("/backend")).toEqual(["/"]);+ test("treats trailing and repeated slashes as the same path", () => {+ expect(covers(sync("/apps"), "/apps/")).toBe(true);+ expect(covers(sync("/apps/payments"), "/apps//payments")).toBe(true);});});-describe("findSecretSyncsCoveringPath", () => {- const folderIdByPath: Record<string, string> = {- "/": "root",- "/apps": "apps",- "/apps/payments": "payments"- };-- const syncs = [- { id: "root-flat", folderId: "root", syncOptions: { includeAllSubFolders: false } },- { id: "apps-recursive", folderId: "apps", syncOptions: { includeAllSubFolders: true } },- { id: "payments-flat", folderId: "payments", syncOptions: {} }- ];-- const toFolder = (path: string) => (folderIdByPath[path] ? { id: folderIdByPath[path], path } : undefined);-- const coveringDeps = {- folderDAL: {- findBySecretPath: async (_projectId: string, _environment: string, path: string) => toFolder(path),- findByManySecretPath: async (queries: { secretPath: string }[]) =>- queries.map(({ secretPath }) => toFolder(secretPath))- },- secretSyncDAL: {- find: vi.fn(async ({ $in }: { $in: { folderId: string[] } }) =>- syncs.filter((sync) => $in.folderId.includes(sync.folderId))- )- }- } as unknown as Parameters<typeof findSecretSyncsCoveringPath>[1];-- const coveringIds = async (secretPath: string) =>- (- await findSecretSyncsCoveringPath(- { projectId: "proj-1", environment: { id: "env-1", slug: "dev" }, secretPath },- coveringDeps- )- )- .map((sync) => sync.id)- .sort();-- test("matches a sync on the path itself whether or not it includes subfolders", async () => {- expect(await coveringIds("/apps/payments")).toEqual(["apps-recursive", "payments-flat"]);+describe("isPathOrDescendantCoveredBySecretSync", () => {+ const sync = (path: string, includeAllSubFolders = false, envId = "env-1") => ({+ environment: { id: envId },+ folder: { path },+ syncOptions: { includeAllSubFolders }});- test("matches a sync on an ancestor only when it includes subfolders", async () => {- expect(await coveringIds("/apps")).toEqual(["apps-recursive"]);- });+ const covers = (entry: ReturnType<typeof sync>, secretPath: string, envId = "env-1") =>+ isPathOrDescendantCoveredBySecretSync(entry, { envId, secretPath });- test("matches ancestors of a path that does not exist yet", async () => {- // A folder being moved lands at a path that has no folder until the move runs.- expect(await coveringIds("/apps/payments/new")).toEqual(["apps-recursive"]);+ test("covers whatever the path itself is covered by", () => {+ expect(covers(sync("/apps"), "/apps")).toBe(true);+ expect(covers(sync("/", true), "/apps")).toBe(true);});- test("matches the root sync for the root path", async () => {- expect(await coveringIds("/")).toEqual(["root-flat"]);+ test("covers a sync rooted anywhere beneath the path, recursive or not", () => {+ expect(covers(sync("/apps/payments"), "/apps")).toBe(true);+ expect(covers(sync("/apps/payments/api", true), "/apps")).toBe(true);+ expect(covers(sync("/apps"), "/")).toBe(true);});- test("returns nothing without querying syncs when no folder on the path exists", async () => {- const find = vi.mocked(coveringDeps.secretSyncDAL.find);- find.mockClear();-- const result = await findSecretSyncsCoveringPath(- { projectId: "proj-1", environment: { id: "env-2", slug: "prod" }, secretPath: "/missing" },- {- ...coveringDeps,- folderDAL: {- findBySecretPath: async () => undefined,- findByManySecretPath: async (queries: unknown[]) => queries.map(() => undefined)- } as unknown as Parameters<typeof findSecretSyncsCoveringPath>[1]["folderDAL"]- }- );-- expect(result).toEqual([]);- expect(find).not.toHaveBeenCalled();+ test("never covers a non-recursive ancestor, a sibling, or another environment", () => {+ expect(covers(sync("/"), "/apps")).toBe(false);+ expect(covers(sync("/apps-legacy/api"), "/apps")).toBe(false);+ expect(covers(sync("/apps/payments", false, "env-2"), "/apps")).toBe(false);});});@@ -195,13 +142,13 @@ describe("toSyncsNewlyCoveringPath", () => {canRead: canReadAll});- expect(result.map((entry) => entry.id)).toEqual(["new"]);+ expect(result.secretSyncs.map((entry) => entry.id)).toEqual(["new"]);});test("returns nothing when the destination is covered only by the source's syncs", () => {expect(toSyncsNewlyCoveringPath({ sourceSyncs: [sync("a")], destinationSyncs: [sync("a")], canRead: canReadAll })- ).toEqual([]);+ ).toEqual({ secretSyncs: [], hasHiddenSecretSyncs: false });});test("orders syncs by name", () => {@@ -211,42 +158,47 @@ describe("toSyncsNewlyCoveringPath", () => {canRead: canReadAll});- expect(result.map((entry) => entry.name)).toEqual(["alpha", "zeta"]);+ expect(result.secretSyncs.map((entry) => entry.name)).toEqual(["alpha", "zeta"]);});test("returns the details of a sync the actor can read", () => {- const [entry] = toSyncsNewlyCoveringPath({+ const { secretSyncs } = toSyncsNewlyCoveringPath({sourceSyncs: [],destinationSyncs: [sync("a", { folder: { path: "/flat" }, syncOptions: {}, isAutoSyncEnabled: false })],canRead: canReadAll});- expect(entry).toEqual({- id: "a",- name: "a",- destination: "aws-parameter-store",- secretPath: "/flat",- includeAllSubFolders: false,- isAutoSyncEnabled: false- });+ expect(secretSyncs).toEqual([+ {+ id: "a",+ name: "a",+ destination: "aws-parameter-store",+ secretPath: "/flat",+ includeAllSubFolders: false,+ isAutoSyncEnabled: false+ }+ ]);});- test("withholds every detail of a sync the actor cannot read, but still reports it", () => {+ test("reports syncs the actor cannot read only as a flag, however many there are", () => {const result = toSyncsNewlyCoveringPath({sourceSyncs: [],- destinationSyncs: [sync("visible"), sync("hidden")],- canRead: (entry) => entry.id !== "hidden"+ destinationSyncs: [sync("visible"), sync("hidden-1"), sync("hidden-2")],+ canRead: (entry) => entry.id === "visible"});- expect(result).toHaveLength(2);- expect(result.find((entry) => entry.id === null)).toEqual({- id: null,- name: null,- destination: null,- secretPath: null,- includeAllSubFolders: null,- isAutoSyncEnabled: null+ expect(result.secretSyncs.map((entry) => entry.id)).toEqual(["visible"]);+ expect(result.hasHiddenSecretSyncs).toBe(true);+ });++ test("does not flag a hidden sync that already covers the source", () => {+ const result = toSyncsNewlyCoveringPath({+ sourceSyncs: [sync("hidden")],+ destinationSyncs: [sync("hidden")],+ canRead: () => false});++ expect(result.hasHiddenSecretSyncs).toBe(false);});});diff --git a/backend/src/services/secret-sync/secret-sync-recursive-fns.ts b/backend/src/services/secret-sync/secret-sync-recursive-fns.tsindex 1826751869..00a7550a5c 100644--- a/backend/src/services/secret-sync/secret-sync-recursive-fns.ts+++ b/backend/src/services/secret-sync/secret-sync-recursive-fns.ts@@ -6,7 +6,6 @@ import { TProjectFolderGrantDALFactory } from "@app/services/project-folder-granimport { TSecretFolderDALFactory } from "@app/services/secret-folder/secret-folder-dal";import { TSecretImportDALFactory } from "@app/services/secret-import/secret-import-dal";import { fnSecretsV2FromImports } from "@app/services/secret-import/secret-import-fns";-import { TSecretSyncDALFactory } from "@app/services/secret-sync/secret-sync-dal";import { SecretSync } from "@app/services/secret-sync/secret-sync-enums";import { SecretSyncError } from "@app/services/secret-sync/secret-sync-errors";import {@@ -30,49 +29,49 @@ export type TFnSecretsV2FromImportsDeps = {kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;};-export const getAncestorPaths = (path: string): string[] => {- const segments = path.split("/").filter(Boolean);-- return segments.map((_, index) => (index === 0 ? "/" : `/${segments.slice(0, index).join("/")}`));-};+const toPathSegments = (path: string) => path.split("/").filter(Boolean);// A sync on the path itself always covers it, whether or not it includes subfolders. A sync on an// ancestor folder only covers it when it includes them. The path need not exist yet: a folder being// moved has no folder at its landing path, and only the recursive syncs above it can cover it there.-export const findSecretSyncsCoveringPath = async (- {- projectId,- environment,- secretPath- }: { projectId: string; environment: { id: string; slug: string }; secretPath: string },- {- folderDAL,- secretSyncDAL- }: {- folderDAL: Pick<TSecretFolderDALFactory, "findBySecretPath" | "findByManySecretPath">;- secretSyncDAL: Pick<TSecretSyncDALFactory, "find">;- }+export const isPathCoveredBySecretSync = (+ sync: {+ environment?: { id: string } | null;+ folder?: { path: string } | null;+ syncOptions?: unknown;+ },+ { envId, secretPath }: { envId: string; secretPath: string }) => {- const folder = await folderDAL.findBySecretPath(projectId, environment.slug, secretPath);+ if (!sync.folder || sync.environment?.id !== envId) return false;- const ancestorFolders = (- await folderDAL.findByManySecretPath(- getAncestorPaths(secretPath).map((path) => ({ envId: environment.id, secretPath: path }))- )- ).filter((entry): entry is NonNullable<typeof entry> => Boolean(entry));+ const syncSegments = toPathSegments(sync.folder.path);+ const pathSegments = toPathSegments(secretPath);- const folderIds = [...ancestorFolders.map((entry) => entry.id), ...(folder ? [folder.id] : [])];- if (!folderIds.length) return [];+ if (syncSegments.length > pathSegments.length) return false;+ if (syncSegments.some((segment, index) => segment !== pathSegments[index])) return false;- const candidateSyncs = await secretSyncDAL.find({ $in: { folderId: folderIds } });-- return candidateSyncs.filter(- (sync) =>- (folder && sync.folderId === folder.id) ||- Boolean((sync.syncOptions as TSecretSync["syncOptions"])?.includeAllSubFolders)+ return (+ syncSegments.length === pathSegments.length ||+ Boolean((sync.syncOptions as TSecretSync["syncOptions"])?.includeAllSubFolders));};+// A move or copy can land items anywhere beneath its destination, so a sync rooted below the destination+// counts as well as one covering it. This can warn about a sync that nothing ends up under, which is+// safer for a warning than missing one.+export const isPathOrDescendantCoveredBySecretSync = (+ sync: Parameters<typeof isPathCoveredBySecretSync>[0],+ { envId, secretPath }: { envId: string; secretPath: string }+) => {+ if (isPathCoveredBySecretSync(sync, { envId, secretPath })) return true;+ if (!sync.folder || sync.environment?.id !== envId) return false;++ const syncSegments = toPathSegments(sync.folder.path);+ const pathSegments = toPathSegments(secretPath);++ return pathSegments.every((segment, index) => syncSegments[index] === segment);+};+type TCoveringSync = {id: string;name: string;@@ -82,8 +81,9 @@ type TCoveringSync = {isAutoSyncEnabled: boolean;};-// A sync that already covers the source is left out, since the item already reaches it. A sync the-// actor cannot read is still reported, so the warning reaches them, but with every detail withheld.+// A sync that already covers the source is left out, since the items already reach it. Syncs the actor+// cannot read collapse into one flag, so the warning still reaches them without revealing how many+// there are or what they cover.export const toSyncsNewlyCoveringPath = <T extends TCoveringSync>({sourceSyncs,destinationSyncs,@@ -94,31 +94,22 @@ export const toSyncsNewlyCoveringPath = <T extends TCoveringSync>({canRead: (sync: T) => boolean;}) => {const sourceSyncIds = new Set(sourceSyncs.map((sync) => sync.id));+ const newSyncs = destinationSyncs.filter((sync) => !sourceSyncIds.has(sync.id));+ const readableSyncs = newSyncs.filter(canRead);- return destinationSyncs- .filter((sync) => !sourceSyncIds.has(sync.id))- .sort((a, b) => a.name.localeCompare(b.name))- .map((sync) => {- if (!canRead(sync)) {- return {- id: null,- name: null,- destination: null,- secretPath: null,- includeAllSubFolders: null,- isAutoSyncEnabled: null- };- }-- return {+ return {+ secretSyncs: readableSyncs+ .sort((a, b) => a.name.localeCompare(b.name))+ .map((sync) => ({id: sync.id,name: sync.name,destination: sync.destination as SecretSync,secretPath: sync.folder?.path ?? null,includeAllSubFolders: Boolean((sync.syncOptions as TSecretSync["syncOptions"])?.includeAllSubFolders),isAutoSyncEnabled: sync.isAutoSyncEnabled- };- });+ })),+ hasHiddenSecretSyncs: readableSyncs.length < newSyncs.length+ };};export const getSyncedFolders = async ({diff --git a/backend/src/services/secret-sync/secret-sync-service.ts b/backend/src/services/secret-sync/secret-sync-service.tsindex e0a01e2cda..f93b4d6438 100644--- a/backend/src/services/secret-sync/secret-sync-service.ts+++ b/backend/src/services/secret-sync/secret-sync-service.ts@@ -36,8 +36,9 @@ import {} from "@app/services/secret-sync/secret-sync-fns";import {buildSyncPayload,- findSecretSyncsCoveringPath,getSyncedFolders,+ isPathCoveredBySecretSync,+ isPathOrDescendantCoveredBySecretSync,toSyncsNewlyCoveringPath} from "@app/services/secret-sync/secret-sync-recursive-fns";import {@@ -437,9 +438,9 @@ export const secretSyncServiceFactory = ({) as TSecretSync[];};- // The syncs that would start sending an item to their destination if it were moved or copied from the- // source path to the destination path. Any project member gets the list, so the warning still reaches- // an actor who cannot read the syncs themselves.+ // The syncs that would start sending items to their destination if they were moved or copied from the+ // source path to the destination path. Any project member gets the warning, so it still reaches an actor+ // who cannot read the syncs themselves.const listSecretSyncsNewlyCoveringPath = async ({projectId,@@ -468,16 +469,14 @@ export const secretSyncServiceFactory = ({if (!destinationEnv)throw new NotFoundError({ message: `Could not find environment with slug "${destinationEnvironment}"` });- const [sourceSyncs, destinationSyncs] = await Promise.all([- findSecretSyncsCoveringPath(- { projectId, environment: sourceEnv, secretPath: sourceSecretPath },- { folderDAL, secretSyncDAL }- ),- findSecretSyncsCoveringPath(- { projectId, environment: destinationEnv, secretPath: destinationSecretPath },- { folderDAL, secretSyncDAL }- )- ]);+ const projectSyncs = await secretSyncDAL.find({ projectId });++ const sourceSyncs = projectSyncs.filter((sync) =>+ isPathCoveredBySecretSync(sync, { envId: sourceEnv.id, secretPath: sourceSecretPath })+ );+ const destinationSyncs = projectSyncs.filter((sync) =>+ isPathOrDescendantCoveredBySecretSync(sync, { envId: destinationEnv.id, secretPath: destinationSecretPath })+ );return toSyncsNewlyCoveringPath({sourceSyncs,diff --git a/frontend/src/components/secret-syncs/SecretSyncMoveWarning.tsx b/frontend/src/components/secret-syncs/SecretSyncMoveWarning.tsxindex a99559afaf..7f03783c1f 100644--- a/frontend/src/components/secret-syncs/SecretSyncMoveWarning.tsx+++ b/frontend/src/components/secret-syncs/SecretSyncMoveWarning.tsx@@ -1,4 +1,4 @@-import { useState } from "react";+import { useEffect, useState } from "react";import { Link } from "@tanstack/react-router";import { ExternalLinkIcon, TriangleAlertIcon } from "lucide-react";@@ -9,14 +9,23 @@ import { SECRET_SYNC_MAP } from "@app/helpers/secretSyncs";import { useGetMoveWarnings } from "@app/hooks/api/dashboard/queries";import { TMoveWarningsCheck } from "@app/hooks/api/dashboard/types";-// the acknowledgement is tied to the checks it was given for, so changing the destination clears it-// and a user never carries a yes over to a path they have not seen the warning for.+// the acknowledgement is tied to the checks and the warning it was given for, and cleared whenever+// either changes, so a yes never carries over to a destination or a set of syncs the user has not seen.export const useSecretSyncMoveWarning = (checks: TMoveWarningsCheck[]) => {const warnings = useGetMoveWarnings(checks);- const checksKey = JSON.stringify(checks);- const [acknowledgedChecksKey, setAcknowledgedChecksKey] = useState<string | null>(null);+ const warningKey = JSON.stringify({+ checks,+ syncIds: warnings.secretSyncs.map(({ id }) => id),+ hasHiddenSecretSyncs: warnings.hasHiddenSecretSyncs,+ hasError: warnings.hasError+ });+ const [acknowledgedWarningKey, setAcknowledgedWarningKey] = useState<string | null>(null);- const isAcknowledged = acknowledgedChecksKey === checksKey;+ useEffect(() => {+ setAcknowledgedWarningKey(null);+ }, [warningKey]);++ const isAcknowledged = acknowledgedWarningKey === warningKey;const needsAcknowledgement =warnings.hasError || warnings.hasHiddenSecretSyncs || warnings.secretSyncs.length > 0;@@ -24,7 +33,7 @@ export const useSecretSyncMoveWarning = (checks: TMoveWarningsCheck[]) => {...warnings,needsAcknowledgement,isAcknowledged,- setIsAcknowledged: (value: boolean) => setAcknowledgedChecksKey(value ? checksKey : null),+ setIsAcknowledged: (value: boolean) => setAcknowledgedWarningKey(value ? warningKey : null),isBlockingSubmit: warnings.isChecking || (needsAcknowledgement && !isAcknowledged)};};@@ -72,7 +81,7 @@ export const SecretSyncMoveWarning = ({ warning, projectId, noun, verb }: Props)<AlertDescription>{hasError && <p>Secret syncs may send these {noun} to external destinations.</p>}{secretSyncs.length > 0 && (- <ul className="list-disc pl-4">+ <ul className="max-h-40 list-disc overflow-y-auto pl-4">{secretSyncs.map((sync) => (<li key={sync.id}><span className="font-medium text-foreground">{sync.name}</span>diff --git a/frontend/src/hooks/api/dashboard/queries.tsx b/frontend/src/hooks/api/dashboard/queries.tsxindex 08e1f23029..fc735c02e8 100644--- a/frontend/src/hooks/api/dashboard/queries.tsx+++ b/frontend/src/hooks/api/dashboard/queries.tsx@@ -779,15 +779,8 @@ export const useGetFoldersMoveDestinationEligibility = (checks: TFolderMoveDesti}});-export type TVisibleMoveWarningSecretSync = TMoveWarningSecretSync & {- id: string;- name: string;- destination: NonNullable<TMoveWarningSecretSync["destination"]>;-};--// fans out one check per (source, destination) pair, since a copy or multi-environment move writes to-// several destinations. syncs the actor cannot read come back without an id, so they cannot be deduped-// across checks and are only reported as present.+// one check per environment pair, since a sync covers one path in one environment. the result is never+// served from cache, so a sync created since the last check is not missed when the dialog reopens.export const useGetMoveWarnings = (checks: TMoveWarningsCheck[]) =>useQueries({queries: checks.map((check) => ({@@ -799,30 +792,22 @@ export const useGetMoveWarnings = (checks: TMoveWarningsCheck[]) =>);return data;},- enabled: Boolean(check.projectId && check.sourceEnvironment && check.destinationEnvironment)+ enabled: Boolean(check.projectId && check.sourceEnvironment && check.destinationEnvironment),+ staleTime: 0,+ gcTime: 0})),combine: (results) => {- const seen = new Set<string>();- const secretSyncs: TVisibleMoveWarningSecretSync[] = [];- let hasHiddenSecretSyncs = false;-- results.forEach(({ data }) => {- data?.secretSyncs.forEach((sync) => {- if (!sync.id || !sync.name || !sync.destination) {- hasHiddenSecretSyncs = true;- return;- }- if (seen.has(sync.id)) return;- seen.add(sync.id);- secretSyncs.push(sync as TVisibleMoveWarningSecretSync);- });- });+ const secretSyncs = new Map<string, TMoveWarningSecretSync>();++ results.forEach(({ data }) =>+ data?.secretSyncs.forEach((sync) => secretSyncs.set(sync.id, sync))+ );return {isChecking: results.some((result) => result.isLoading),hasError: results.some((result) => result.isError),- secretSyncs,- hasHiddenSecretSyncs+ secretSyncs: [...secretSyncs.values()],+ hasHiddenSecretSyncs: results.some(({ data }) => data?.hasHiddenSecretSyncs)};}});diff --git a/frontend/src/hooks/api/dashboard/types.ts b/frontend/src/hooks/api/dashboard/types.tsindex 9c15380e09..e757eca0c0 100644--- a/frontend/src/hooks/api/dashboard/types.ts+++ b/frontend/src/hooks/api/dashboard/types.ts@@ -286,7 +286,6 @@ export type FolderMoveEligibilityResponse = {hasRbacPolicies?: boolean;};-// for a folder, the paths are the folder's own path and the path it will have once movedexport type TMoveWarningsCheck = {projectId: string;sourceEnvironment: string;@@ -295,18 +294,18 @@ export type TMoveWarningsCheck = {destinationSecretPath: string;};-// every field is null when the actor cannot read the syncexport type TMoveWarningSecretSync = {- id: string | null;- name: string | null;- destination: SecretSync | null;+ id: string;+ name: string;+ destination: SecretSync;secretPath: string | null;- includeAllSubFolders: boolean | null;- isAutoSyncEnabled: boolean | null;+ includeAllSubFolders: boolean;+ isAutoSyncEnabled: boolean;};export type TMoveWarningsResponse = {secretSyncs: TMoveWarningSecretSync[];+ hasHiddenSecretSyncs: boolean;};export type TFolderMoveDestinationCheck = {diff --git a/frontend/src/pages/secret-manager/OverviewPage/components/CopySecretsSheet/CopySecretsSheet.tsx b/frontend/src/pages/secret-manager/OverviewPage/components/CopySecretsSheet/CopySecretsSheet.tsxindex 92a8b2784f..6ff82b983e 100644--- a/frontend/src/pages/secret-manager/OverviewPage/components/CopySecretsSheet/CopySecretsSheet.tsx+++ b/frontend/src/pages/secret-manager/OverviewPage/components/CopySecretsSheet/CopySecretsSheet.tsx@@ -201,14 +201,17 @@ const CopySecretsSession = ({sourceEnvironmentSlug &&destinationEnvironmentSlug &&isSourcePathSettled &&- isDestinationPathSettled- ? requestGroups.map((group) => ({- projectId,- sourceEnvironment: sourceEnvironmentSlug,- sourceSecretPath: group.sourcePath,- destinationEnvironment: destinationEnvironmentSlug,- destinationSecretPath: group.destinationPath- }))+ isDestinationPathSettled &&+ (requestGroups.length || selectedFolderPaths.length)+ ? [+ {+ projectId,+ sourceEnvironment: sourceEnvironmentSlug,+ sourceSecretPath: normalizedSourcePath,+ destinationEnvironment: destinationEnvironmentSlug,+ destinationSecretPath: normalizedDestinationPath+ }+ ]: []);const destinationFolderPaths = getCopyDestinationFolderPaths({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.tsxindex bc91d1a6ba..b1b294a9d9 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@@ -545,9 +545,8 @@ const buildDestinationTargets = ({return { checks: isSelfMove ? [] : checks, isSelfMove };};-// a secret lands in the destination folder itself, a folder at the destination folder plus its own name.-// each secret environment and each moved folder gets its own check, since a sync covers one path in one-// environment.+// one check per environment pair that has something to move. the backend counts syncs beneath the+// destination too, so a moved folder needs no check of its own.const buildMoveWarningChecks = ({projectId,sourceSecretPath,@@ -563,25 +562,20 @@ const buildMoveWarningChecks = ({}): TMoveWarningsCheck[] => {if (!destinationPath) return [];- const destination = removeTrailingSlash(destinationPath);- const base = removeTrailingSlash(sourceSecretPath);+ const environmentPairs = new Map(+ [...secretEnvironments, ...movedFolders].map(({ sourceEnv, destinationEnvironment }) => [+ `${sourceEnv}:${destinationEnvironment}`,+ { sourceEnv, destinationEnvironment }+ ])+ );- return [- ...secretEnvironments.map(({ sourceEnv, destinationEnvironment }) => ({- projectId,- sourceEnvironment: sourceEnv,- sourceSecretPath: base,- destinationEnvironment,- destinationSecretPath: destination- })),- ...movedFolders.map(({ folderName, sourceEnv, destinationEnvironment }) => ({- projectId,- sourceEnvironment: sourceEnv,- sourceSecretPath: joinSecretPath(base, folderName),- destinationEnvironment,- destinationSecretPath: joinSecretPath(destination, folderName)- }))- ];+ return [...environmentPairs.values()].map(({ sourceEnv, destinationEnvironment }) => ({+ projectId,+ sourceEnvironment: sourceEnv,+ sourceSecretPath: removeTrailingSlash(sourceSecretPath),+ destinationEnvironment,+ destinationSecretPath: removeTrailingSlash(destinationPath)+ }));};// memoizes the destination checks for the moved folders and runs the destination approval-policy eligibility