Skip to content

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

test(secret-sync): make the spec pass and each test independent

Calvina62ea97da265
diff --git a/backend/e2e-test/fakes/aws-connection-fns.ts b/backend/e2e-test/fakes/aws-connection-fns.ts
index be22ca9c47..54c257565b 100644
--- a/backend/e2e-test/fakes/aws-connection-fns.ts
+++ b/backend/e2e-test/fakes/aws-connection-fns.ts
@@ -23,11 +23,20 @@ type TFakeAwsConnectionState = {
validationError: string | null;
};
-const state: TFakeAwsConnectionState = {
+// Shared through globalThis for the same reason as the Parameter Store fake: the alias makes
+// this module reachable by more than one specifier, so it can be instantiated twice, and a
+// spec would then configure a copy the server never reads.
+const globalScope = globalThis as typeof globalThis & {
+ infisicalFakeAwsConnection?: TFakeAwsConnectionState;
+};
+
+globalScope.infisicalFakeAwsConnection ??= {
accountId: DEFAULT_ACCOUNT_ID,
validationError: null
};
+const state = globalScope.infisicalFakeAwsConnection;
+
// Behavior a spec can change. Every field resets between test files, so a spec never inherits
// another's configuration. See e2e-test/setup/reset-fakes.ts.
export const fakeAwsConnection = {
diff --git a/backend/e2e-test/fakes/aws-parameter-store-sync-fns.ts b/backend/e2e-test/fakes/aws-parameter-store-sync-fns.ts
index 2f36068ec7..e05da7c669 100644
--- a/backend/e2e-test/fakes/aws-parameter-store-sync-fns.ts
+++ b/backend/e2e-test/fakes/aws-parameter-store-sync-fns.ts
@@ -20,7 +20,19 @@ type TFakeStore = {
runCount: number;
};
-const stores = new Map<string, TFakeStore>();
+// The state hangs off globalThis rather than module scope on purpose. The alias makes this
+// module reachable by more than one specifier (the server reaches it through the barrel's
+// relative import, a spec through its own path), and the bundler then instantiates it twice:
+// the sync writes to one copy of the store while the spec reads an empty other one, and the
+// only symptom is an assertion that never comes true. Sharing through globalThis makes that
+// impossible, and matches how the harness already shares testServer and testDb.
+const globalScope = globalThis as typeof globalThis & {
+ infisicalFakeParameterStore?: Map<string, TFakeStore>;
+};
+
+globalScope.infisicalFakeParameterStore ??= new Map<string, TFakeStore>();
+
+const stores = globalScope.infisicalFakeParameterStore;
const storeKeyFor = (region: string, path: string) => `${region}|${path}`;
diff --git a/backend/e2e-test/routes/v1/secret-sync.spec.ts b/backend/e2e-test/routes/v1/secret-sync.spec.ts
index 24c228602a..3af3782100 100644
--- a/backend/e2e-test/routes/v1/secret-sync.spec.ts
+++ b/backend/e2e-test/routes/v1/secret-sync.spec.ts
@@ -1,3 +1,4 @@
+import { randomUUID } from "crypto";
import { fakeParameterStore } from "e2e-test/fakes/aws-parameter-store-sync-fns";
import { createFolder, deleteFolder } from "e2e-test/testUtils/folders";
import { createSecretImport } from "e2e-test/testUtils/secret-imports";
@@ -5,10 +6,13 @@ import {
createAwsAppConnection,
createSecretSync,
deleteAppConnection,
- expectNoSyncRun,
+ deleteSecretSync,
+ expectDestinationUnchanged,
importSecretsForSync,
removeSecretsForSync,
- triggerSecretSync
+ setAutoSync,
+ triggerSecretSync,
+ waitForDestinationSecrets
} from "e2e-test/testUtils/secret-syncs";
import { createSecretV2, deleteSecretV2, getSecretsV2 } from "e2e-test/testUtils/secrets";
@@ -31,54 +35,23 @@ const ENV = "dev";
const pathFor = (name: string) => `/${name}/`;
describe("Secret syncs", async () => {
+ // A sync run is a queue round trip, so it takes longer than the 5s default. The helpers give
+ // up after 20s of their own, and this has to outlast that or the test dies first and reports
+ // a timeout instead of whatever the sync actually did.
+ vi.setConfig({ testTimeout: 30_000, hookTimeout: 30_000 });
+
let projectId: string;
let connectionId: string;
+ let createdSyncIds: string[] = [];
- beforeAll(async () => {
- const projectRes = await testServer.inject({
- method: "POST",
- url: "/api/v1/projects",
- headers: { authorization: `Bearer ${jwtAuthToken}` },
- body: { projectName: `secret-sync-e2e-${Date.now()}` }
- });
- expect(projectRes.statusCode).toBe(200);
- projectId = projectRes.json().project.id as string;
-
- // Connections are org-scoped while syncs are project-scoped, so the name has to be unique
- // across the whole shared seeded org.
- connectionId = await createAwsAppConnection({
- name: `secret-sync-e2e-${Date.now()}`,
- authToken: jwtAuthToken
- });
-
- await createFolder({
- authToken: jwtAuthToken,
- workspaceId: projectId,
- environmentSlug: ENV,
- secretPath: "/",
- name: "services"
- });
- await createFolder({
+ const newFolder = (parentPath: string, name: string) =>
+ createFolder({
authToken: jwtAuthToken,
workspaceId: projectId,
environmentSlug: ENV,
- secretPath: "/services",
- name: "api"
+ secretPath: parentPath,
+ name
});
- });
-
- afterAll(async () => {
- await deleteAppConnection({ connectionId, authToken: jwtAuthToken });
- await testServer.inject({
- method: "DELETE",
- url: `/api/v1/projects/${projectId}`,
- headers: { authorization: `Bearer ${jwtAuthToken}` }
- });
- });
-
- beforeEach(() => {
- fakeParameterStore.reset();
- });
const addSecret = (secretPath: string, key: string, value: string) =>
createSecretV2({ authToken: jwtAuthToken, workspaceId: projectId, environmentSlug: ENV, secretPath, key, value });
@@ -111,9 +84,59 @@ describe("Secret syncs", async () => {
...overrides
});
+ // Tracked so afterEach can clear them before the connection. Absent when a test asserts
+ // that creation is refused.
+ if (result.secretSync) createdSyncIds.push(result.secretSync.id);
+
return result;
};
+ // Everything a test touches is built here and torn down after it, so no test can be reached by
+ // another's writes or teardown. That matters more than usual for secret syncs: auto sync reacts
+ // to any write at a sync's source path, secret imports outlive the test that made them, and an
+ // app connection is org-scoped rather than project-scoped, so sharing one would leave a single
+ // row that every test's syncs hang off.
+ beforeEach(async () => {
+ fakeParameterStore.reset();
+ createdSyncIds = [];
+
+ const suffix = randomUUID().slice(0, 8);
+
+ const projectRes = await testServer.inject({
+ method: "POST",
+ url: "/api/v1/projects",
+ headers: { authorization: `Bearer ${jwtAuthToken}` },
+ body: { projectName: `secret-sync-e2e-${suffix}` }
+ });
+ expect(projectRes.statusCode).toBe(200);
+ projectId = projectRes.json().project.id as string;
+
+ connectionId = await createAwsAppConnection({
+ name: `secret-sync-e2e-${suffix}`,
+ authToken: jwtAuthToken
+ });
+
+ await newFolder("/", "services");
+ await newFolder("/services", "api");
+ });
+
+ afterEach(async () => {
+ // Order matters. A sync holds a foreign key to the connection, and deleting a project only
+ // soft deletes it, leaving the sync rows in place, so the connection delete would fail on the
+ // constraint if the syncs went second.
+ 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: { authorization: `Bearer ${jwtAuthToken}` }
+ });
+ });
+
describe("A sync sends the secrets of its own source environment and secret path", () => {
test("A sync sends the secrets of its source secret path", async () => {
await addSecret("/services", "API_KEY", "api-value");
@@ -361,7 +384,9 @@ describe("Secret syncs", async () => {
});
test("An import fails when a destination secret key is not a valid Infisical secret key", async () => {
- fakeParameterStore.at(REGION, pathFor("import-invalid-name")).seed({ "not a valid key": "destination-value" });
+ // SecretNameSchema rejects only a colon or a forward slash, so a name with spaces would
+ // import cleanly. This has to be one Infisical genuinely refuses.
+ fakeParameterStore.at(REGION, pathFor("import-invalid-name")).seed({ "BAD:KEY": "destination-value" });
const { secretSync } = await newSync("import-invalid-name", { secretPath: "/services" });
const { secretSync: imported } = await importSecretsForSync({
@@ -402,44 +427,54 @@ describe("Secret syncs", async () => {
describe("Automatic syncing is triggered by changes at the source secret path only", () => {
test("Creating a secret at the source secret path triggers a sync run", async () => {
const destinationPath = pathFor("auto-sync-source");
+ // Auto sync is enabled after creation, and only once the destination has gone quiet, so
+ // exactly one run can be in flight when the write below happens.
const { secretSync } = await newSync("auto-sync-source", {
secretPath: "/services",
- isAutoSyncEnabled: true
+ isAutoSyncEnabled: false
});
+ await setAutoSync({ syncId: secretSync!.id, isAutoSyncEnabled: true, authToken: jwtAuthToken });
- // Creating the sync with auto sync on already queues one run; wait it out so the run this
- // test cares about is the one the secret write causes.
- await triggerSecretSync({ syncId: secretSync!.id, region: REGION, destinationPath, authToken: jwtAuthToken });
- const runCountBefore = fakeParameterStore.at(REGION, destinationPath).runCount();
-
+ // No explicit trigger: the write alone has to cause the run, which is the behaviour
+ // under test.
await addSecret("/services", "NEW_KEY", "new-value");
- await triggerSecretSync({ syncId: secretSync!.id, region: REGION, destinationPath, authToken: jwtAuthToken });
- expect(fakeParameterStore.at(REGION, destinationPath).runCount()).toBeGreaterThan(runCountBefore);
- expect(fakeParameterStore.at(REGION, destinationPath).read()).toEqual({ NEW_KEY: "new-value" });
-
- await removeSecret("/services", "NEW_KEY");
+ await waitForDestinationSecrets({
+ region: REGION,
+ destinationPath,
+ expected: { NEW_KEY: "new-value" }
+ });
});
// The second pin for recursive syncing: today a child folder write reaches nothing.
test("Creating a secret in a child secret path does not trigger a sync run", async () => {
const destinationPath = pathFor("auto-sync-child");
- await addSecret("/services", "PARENT_KEY", "parent-value");
-
+ // Written before auto sync is on, so it cannot queue a run that lands later and looks
+ // like the child write's doing.
const { secretSync } = await newSync("auto-sync-child", {
secretPath: "/services",
- isAutoSyncEnabled: true
+ isAutoSyncEnabled: false
});
- await triggerSecretSync({ syncId: secretSync!.id, region: REGION, destinationPath, authToken: jwtAuthToken });
- const runCountBefore = fakeParameterStore.at(REGION, destinationPath).runCount();
+ await addSecret("/services", "PARENT_KEY", "parent-value");
- await addSecret("/services/api", "CHILD_KEY", "child-value");
+ // Enabling auto sync queues a run; wait for the parent's secret to arrive.
+ await setAutoSync({ syncId: secretSync!.id, isAutoSyncEnabled: true, authToken: jwtAuthToken });
+ await waitForDestinationSecrets({
+ region: REGION,
+ destinationPath,
+ expected: { PARENT_KEY: "parent-value" }
+ });
- await expectNoSyncRun({ region: REGION, destinationPath, runCountBefore });
- expect(fakeParameterStore.at(REGION, destinationPath).read()).toEqual({ PARENT_KEY: "parent-value" });
+ await addSecret("/services/api", "CHILD_KEY", "child-value");
- await removeSecret("/services", "PARENT_KEY");
- await removeSecret("/services/api", "CHILD_KEY");
+ // The child's secret must not reach the destination. Whether the parent's sync happens to
+ // run again is not asserted: the queue requeues on lock contention, so run counts are not
+ // stable, while what arrives is.
+ await expectDestinationUnchanged({
+ region: REGION,
+ destinationPath,
+ expected: { PARENT_KEY: "parent-value" }
+ });
});
test("A change at the source secret path does not trigger a sync run when the auto sync parameter is false", async () => {
@@ -448,10 +483,7 @@ describe("Secret syncs", async () => {
await addSecret("/services", "NEW_KEY", "new-value");
- await expectNoSyncRun({ region: REGION, destinationPath, runCountBefore: 0 });
- expect(fakeParameterStore.at(REGION, destinationPath).read()).toEqual({});
-
- await removeSecret("/services", "NEW_KEY");
+ await expectDestinationUnchanged({ region: REGION, destinationPath, expected: {} });
});
});
diff --git a/backend/e2e-test/testUtils/secret-syncs.ts b/backend/e2e-test/testUtils/secret-syncs.ts
index 31221c0809..c980e31f8d 100644
--- a/backend/e2e-test/testUtils/secret-syncs.ts
+++ b/backend/e2e-test/testUtils/secret-syncs.ts
@@ -98,6 +98,22 @@ export const createSecretSync = async (dto: {
return { secretSync: res.json().secretSync as TSecretSyncRecord };
};
+// Turning auto sync on after the fact, rather than at creation, is what lets a spec keep a
+// single run in flight. Sync creation with auto sync on queues a run immediately, and a second
+// run racing it loses the sync lock and gets requeued by $handleAcquireLockFailure, landing
+// later at an unpredictable time and spoiling any count.
+export const setAutoSync = async (dto: { syncId: string; isAutoSyncEnabled: boolean; authToken: string }) => {
+ const res = await testServer.inject({
+ method: "PATCH",
+ url: `/api/v1/secret-syncs/${DESTINATION}/${dto.syncId}`,
+ headers: { authorization: `Bearer ${dto.authToken}` },
+ body: { isAutoSyncEnabled: dto.isAutoSyncEnabled }
+ });
+
+ expect(res.statusCode).toBe(200);
+ return res.json().secretSync as TSecretSyncRecord;
+};
+
export const getSecretSync = async (dto: { syncId: string; authToken: string }) => {
const res = await testServer.inject({
method: "GET",
@@ -192,7 +208,8 @@ export const importSecretsForSync = async (dto: {
method: "POST",
url: `/api/v1/secret-syncs/${DESTINATION}/${dto.syncId}/import-secrets`,
headers: { authorization: `Bearer ${dto.authToken}` },
- body: { importBehavior: dto.importBehavior }
+ // A querystring parameter on this route, not a body field.
+ query: { importBehavior: dto.importBehavior }
});
expect(res.statusCode).toBe(dto.expectStatusCode ?? 200);
@@ -224,17 +241,40 @@ export const removeSecretsForSync = async (dto: { syncId: string; authToken: str
});
};
-// A spec that expects no sync run has to wait out a window in which one could have happened;
-// asserting an absence immediately would pass simply because nothing had run yet.
-export const expectNoSyncRun = async (dto: {
+// Waits for the destination to hold exactly these secrets. Use this rather than a run count
+// when the meaningful signal is what arrived: a count cannot tell "the run has not happened
+// yet" from "the runs have finished", and both look identical the instant a write returns.
+export const waitForDestinationSecrets = async (dto: {
region: string;
destinationPath: string;
- runCountBefore: number;
+ expected: Record<string, string>;
+}) => {
+ const expected = JSON.stringify(dto.expected, Object.keys(dto.expected).sort());
+ const describeExpected = Object.keys(dto.expected).join(",") || "nothing";
+
+ return pollUntil({
+ describe: `the destination at ${dto.region}${dto.destinationPath} to hold ${describeExpected}`,
+ read: () => fakeParameterStore.at(dto.region, dto.destinationPath).read(),
+ done: (actual) => JSON.stringify(actual, Object.keys(actual).sort()) === expected
+ });
+};
+
+// Asserts the destination still holds exactly these secrets after a window in which a sync
+// could have run.
+//
+// Deliberately about content rather than run counts. A count of runs is not a stable property
+// of this system: the queue retries a failed job and $handleAcquireLockFailure requeues one
+// that lost the sync lock, both after a delay, so "exactly one more run" holds or fails
+// depending on timing. What is stable, and what a user would notice, is what arrived.
+export const expectDestinationUnchanged = async (dto: {
+ region: string;
+ destinationPath: string;
+ expected: Record<string, string>;
windowMs?: number;
}) => {
await new Promise((resolve) => {
- setTimeout(resolve, dto.windowMs ?? 2_000);
+ setTimeout(resolve, dto.windowMs ?? 3_000);
});
- expect(fakeParameterStore.at(dto.region, dto.destinationPath).runCount()).toBe(dto.runCountBefore);
+ expect(fakeParameterStore.at(dto.region, dto.destinationPath).read()).toEqual(dto.expected);
};
diff --git a/docker-compose.test.yml b/docker-compose.test.yml
index 9610d6f08a..02110410c7 100644
--- a/docker-compose.test.yml
+++ b/docker-compose.test.yml
@@ -69,7 +69,11 @@ services:
AUTH_SECRET: something-random
ENCRYPTION_KEY: p5e5k2j3+HIErjm02dzSrlhXc1xhdgoWvC6pox410rE=
NODE_ENV: test
- NODE_OPTIONS: --force-fips
+ # The heap is set explicitly because Node derives its default from available memory, so
+ # without this the suite's budget depends on the host: a 16GB CI runner gets about 4GB
+ # and boots fine, while an 8GB Docker Desktop VM gets ~2GB and dies during environment
+ # setup, before a single spec runs. Booting the whole server needs more than 2GB.
+ NODE_OPTIONS: --force-fips --max-old-space-size=4096
TELEMETRY_ENABLED: "false"
# The secret rotation specs need these plus `docker compose -f docker-compose.e2e-dbs.yml
# up -d`. Left empty otherwise, which is how a run without them behaves anyway.