Skip to content

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

feat(secret-sync): trigger recursive syncs when a subfolder changes

Calvindea2c4ad7596
diff --git a/backend/e2e-test/routes/v1/secret-sync-recursive-trigger.spec.ts b/backend/e2e-test/routes/v1/secret-sync-recursive-trigger.spec.ts
new file mode 100644
index 0000000000..787e52b877
--- /dev/null
+++ b/backend/e2e-test/routes/v1/secret-sync-recursive-trigger.spec.ts
@@ -0,0 +1,184 @@
+import { randomUUID } from "node:crypto";
+
+import { fakeParameterStore } from "e2e-test/fakes/aws-parameter-store-sync-fns";
+import { createFolder } from "e2e-test/testUtils/folders";
+import {
+ createAwsAppConnection,
+ createSecretSync,
+ deleteAppConnection,
+ deleteSecretSync,
+ expectDestinationUnchanged,
+ setAutoSync,
+ waitForDestinationSecrets,
+ waitForSyncRun
+} from "e2e-test/testUtils/secret-syncs";
+import { createSecretV2 } from "e2e-test/testUtils/secrets";
+
+import { initEnvConfig } from "@app/lib/config/env";
+import { initLogger, logger } from "@app/lib/logger";
+import { SecretSyncInitialSyncBehavior } from "@app/services/secret-sync/secret-sync-enums";
+
+// A write inside a recursive sync's subtree must still queue that sync, and a write inside a
+// non-recursive sync's subtree must not queue it. Both halves matter equally: the first is the
+// bug (auto-sync silently stops covering subfolders), the second guards against over-triggering
+// (syncing secrets the sync was never configured to cover).
+//
+// Each test waits for the auto-sync-enable run to finish (via waitForSyncRun) before writing the
+// subfolder secret. Skipping that wait would let the enable-time run, which always resolves the
+// full recursive subtree at whatever the DB holds when it executes, pick up the later write by
+// coincidence and mask a missing trigger.
+
+const ENV = "dev";
+const REGION = "us-east-1";
+
+const adminHeaders = { authorization: `Bearer ${jwtAuthToken}` };
+
+describe("A write in a subfolder triggers only the recursive sync above it", async () => {
+ vi.setConfig({ testTimeout: 30_000, hookTimeout: 30_000 });
+
+ let projectId: string;
+ let connectionId: string;
+ const createdSyncIds: string[] = [];
+
+ beforeAll(async () => {
+ initLogger();
+ await initEnvConfig(testHsmService, testKmsRootConfigDAL, testSuperAdminDAL, logger);
+
+ const suffix = randomUUID().slice(0, 8);
+
+ const projectRes = await testServer.inject({
+ method: "POST",
+ url: "/api/v1/projects",
+ headers: adminHeaders,
+ body: { projectName: `secret-sync-recursive-trigger-${suffix}` }
+ });
+ expect(projectRes.statusCode).toBe(200);
+ projectId = projectRes.json().project.id as string;
+
+ connectionId = await createAwsAppConnection({
+ name: `secret-sync-recursive-trigger-${suffix}`,
+ authToken: jwtAuthToken
+ });
+
+ await createFolder({
+ authToken: jwtAuthToken,
+ workspaceId: projectId,
+ environmentSlug: ENV,
+ secretPath: "/",
+ name: "backend"
+ });
+ await createFolder({
+ authToken: jwtAuthToken,
+ workspaceId: projectId,
+ environmentSlug: ENV,
+ secretPath: "/backend",
+ name: "api"
+ });
+ });
+
+ afterAll(async () => {
+ for (const syncId of createdSyncIds) {
+ // eslint-disable-next-line no-await-in-loop
+ await deleteSecretSync({ syncId, authToken: jwtAuthToken });
+ }
+
+ await deleteAppConnection({ connectionId, authToken: jwtAuthToken });
+ await testServer.inject({
+ method: "DELETE",
+ url: `/api/v1/projects/${projectId}`,
+ headers: adminHeaders
+ });
+ });
+
+ test("a write at a subfolder reaches the recursive sync rooted above it", async () => {
+ const destinationPath = "/recursive-trigger-target/";
+
+ const { secretSync } = await createSecretSync({
+ name: "recursive-trigger",
+ projectId,
+ connectionId,
+ environmentSlug: ENV,
+ secretPath: "/backend",
+ region: REGION,
+ destinationPath,
+ initialSyncBehavior: SecretSyncInitialSyncBehavior.OverwriteDestination,
+ recursive: true,
+ isAutoSyncEnabled: false,
+ authToken: jwtAuthToken
+ });
+ createdSyncIds.push(secretSync!.id);
+
+ const runCountBeforeEnable = fakeParameterStore.at(REGION, destinationPath).runCount();
+ await setAutoSync({ syncId: secretSync!.id, isAutoSyncEnabled: true, authToken: jwtAuthToken });
+ await waitForSyncRun({
+ syncId: secretSync!.id,
+ region: REGION,
+ destinationPath,
+ runCountBefore: runCountBeforeEnable,
+ authToken: jwtAuthToken
+ });
+
+ expect(fakeParameterStore.at(REGION, destinationPath).read()).toEqual({});
+
+ await createSecretV2({
+ authToken: jwtAuthToken,
+ workspaceId: projectId,
+ environmentSlug: ENV,
+ secretPath: "/backend/api",
+ key: "SUBFOLDER_KEY",
+ value: "subfolder-value"
+ });
+
+ await waitForDestinationSecrets({
+ region: REGION,
+ destinationPath,
+ expected: { SUBFOLDER_KEY: "subfolder-value" }
+ });
+ });
+
+ test("a write at a subfolder does not reach a non-recursive sync rooted above it", async () => {
+ const destinationPath = "/non-recursive-trigger-target/";
+
+ const { secretSync } = await createSecretSync({
+ name: "non-recursive-trigger",
+ projectId,
+ connectionId,
+ environmentSlug: ENV,
+ secretPath: "/backend",
+ region: REGION,
+ destinationPath,
+ initialSyncBehavior: SecretSyncInitialSyncBehavior.OverwriteDestination,
+ recursive: false,
+ isAutoSyncEnabled: false,
+ authToken: jwtAuthToken
+ });
+ createdSyncIds.push(secretSync!.id);
+
+ const runCountBeforeEnable = fakeParameterStore.at(REGION, destinationPath).runCount();
+ await setAutoSync({ syncId: secretSync!.id, isAutoSyncEnabled: true, authToken: jwtAuthToken });
+ await waitForSyncRun({
+ syncId: secretSync!.id,
+ region: REGION,
+ destinationPath,
+ runCountBefore: runCountBeforeEnable,
+ authToken: jwtAuthToken
+ });
+
+ expect(fakeParameterStore.at(REGION, destinationPath).read()).toEqual({});
+
+ await createSecretV2({
+ authToken: jwtAuthToken,
+ workspaceId: projectId,
+ environmentSlug: ENV,
+ secretPath: "/backend/api",
+ key: "API_KEY",
+ value: "api-value"
+ });
+
+ await expectDestinationUnchanged({
+ region: REGION,
+ destinationPath,
+ expected: {}
+ });
+ });
+});
diff --git a/backend/src/services/secret-sync/secret-sync-queue.ts b/backend/src/services/secret-sync/secret-sync-queue.ts
index 9bb8007484..e3f3673f97 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 } from "@app/services/secret-sync/secret-sync-recursive-fns";
+import { buildSyncPayload, getAncestorPaths } from "@app/services/secret-sync/secret-sync-recursive-fns";
import {
SecretSyncAction,
SecretSyncStatus,
@@ -1061,7 +1061,23 @@ export const secretSyncQueueFactory = ({
`Could not find folder at path "${secretPath}" for environment with slug "${environmentSlug}" in project with ID "${projectId}"`
);
- const secretSyncs = await secretSyncDAL.find({ folderId: folder.id, isAutoSyncEnabled: true });
+ const ancestorPaths = getAncestorPaths(secretPath);
+
+ const ancestorFolders = (
+ await folderDAL.findByManySecretPath(ancestorPaths.map((path) => ({ envId: folder.envId, secretPath: path })))
+ ).filter((entry): entry is NonNullable<typeof entry> => Boolean(entry));
+
+ const candidateSyncs = await secretSyncDAL.find({
+ $in: { folderId: [...ancestorFolders.map((entry) => entry.id), folder.id] },
+ isAutoSyncEnabled: true
+ });
+
+ // A sync on the changed folder itself always matches, recursive or not. A sync on an
+ // ancestor folder only matches when it is recursive, so a non-recursive sync rooted above
+ // this path is never triggered by a write it was never configured to cover.
+ const secretSyncs = candidateSyncs.filter(
+ (sync) => sync.folderId === folder.id || Boolean((sync.syncOptions as { recursive?: boolean } | null)?.recursive)
+ );
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.ts
index c1ac33c6a9..9f492f19b8 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,6 +1,7 @@
import {
assertWithinSecretLimit,
buildSyncPayload,
+ getAncestorPaths,
mergeImportedSecrets,
resolveSyncFolders,
SECRET_SYNC_MAX_SECRETS
@@ -44,6 +45,20 @@ describe("resolveSyncFolders", () => {
});
});
+describe("getAncestorPaths", () => {
+ test("returns the root for a top-level path", () => {
+ expect(getAncestorPaths("/")).toEqual([]);
+ });
+
+ test("returns every ancestor, closest last", () => {
+ expect(getAncestorPaths("/backend/api/v2")).toEqual(["/", "/backend", "/backend/api"]);
+ });
+
+ test("returns the root for a single-segment path", () => {
+ expect(getAncestorPaths("/backend")).toEqual(["/"]);
+ });
+});
+
describe("assertWithinSecretLimit", () => {
test("accepts a count at the limit", () => {
expect(() => assertWithinSecretLimit(SECRET_SYNC_MAX_SECRETS)).not.toThrow();
diff --git a/backend/src/services/secret-sync/secret-sync-recursive-fns.ts b/backend/src/services/secret-sync/secret-sync-recursive-fns.ts
index e73ae2fba3..409fb6bd92 100644
--- a/backend/src/services/secret-sync/secret-sync-recursive-fns.ts
+++ b/backend/src/services/secret-sync/secret-sync-recursive-fns.ts
@@ -30,6 +30,12 @@ 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("/")}`));
+};
+
export const SECRET_SYNC_MAX_SECRETS = 10_000;
export const assertWithinSecretLimit = (count: number) => {