Skip to content

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

fix secret clean up

Thiago Araujo da Silva5a80f4b309b6
diff --git a/backend/e2e-test/routes/v1/secret-replication.spec.ts b/backend/e2e-test/routes/v1/secret-replication.spec.ts
index 395758b92a..33476e3108 100644
--- a/backend/e2e-test/routes/v1/secret-replication.spec.ts
+++ b/backend/e2e-test/routes/v1/secret-replication.spec.ts
@@ -1,46 +1,26 @@
import { createFolder, deleteFolder } from "e2e-test/testUtils/folders";
import { createSecretImport, deleteSecretImport } from "e2e-test/testUtils/secret-imports";
-import { createSecretV2, deleteSecretV2, getSecretByNameV2, getSecretsV2 } from "e2e-test/testUtils/secrets";
+import { createSecretV2, deleteSecretV2, getSecretsV2, waitForReplicatedSecret } from "e2e-test/testUtils/secrets";
import { seedData1 } from "@app/db/seed-data";
-// Replication runs asynchronously through BullMQ, so the imported secret shows
-// up some time after the write. Poll for it instead of sleeping a fixed 10s: a
-// fixed wait is simultaneously too short (it flakes whenever CI contention
-// pushes replication past the deadline) and too long (it burns the full 10s on
-// every pass, even though replication usually lands in well under a second).
-const REPLICATION_TIMEOUT_MS = 25_000;
-const REPLICATION_POLL_MS = 250;
-
-const waitForReplicatedSecret = async (dto: {
- workspaceId: string;
- environmentSlug: string;
- secretPath: string;
- key: string;
- value: string;
- authToken: string;
-}) => {
- const deadline = Date.now() + REPLICATION_TIMEOUT_MS;
- for (;;) {
- try {
- // eslint-disable-next-line no-await-in-loop
- const secret = await getSecretByNameV2(dto);
- if (secret.secretValue === dto.value) return secret;
- } catch {
- // Not replicated yet — getSecretByNameV2 asserts on a 200.
- }
- if (Date.now() >= deadline) {
- throw new Error(
- `Timed out after ${REPLICATION_TIMEOUT_MS}ms waiting for "${dto.key}" to replicate into ${dto.environmentSlug}${dto.secretPath}`
- );
- }
- // eslint-disable-next-line no-await-in-loop
- await new Promise((resolve) => {
- setTimeout(resolve, REPLICATION_POLL_MS);
- });
- }
+// Source secrets are torn down after the test that created them. Cleanup used
+// to sit at the end of each test body, so a failing assertion skipped it and
+// left the source secret in place — and since every test here replicates into
+// the same shared environments, the leftovers then showed up in later tests'
+// assertions as phantom imports.
+const createdSecrets: Parameters<typeof deleteSecretV2>[0][] = [];
+
+const createTrackedSecret = async (dto: Parameters<typeof createSecretV2>[0]) => {
+ const secret = await createSecretV2(dto);
+ createdSecrets.push(dto);
+ return secret;
};
+afterEach(async () => {
+ await Promise.all(createdSecrets.splice(0).map((el) => deleteSecretV2(el)));
+});
+
// dev <- stage <- prod
describe.each([{ secretPath: "/" }, { secretPath: "/deep" }])(
"Secret replication waterfall pattern testing - %secretPath",
@@ -146,7 +126,7 @@ describe.each([{ secretPath: "/" }, { secretPath: "/deep" }])(
});
test("Check one level imported secret exist", async () => {
- await createSecretV2({
+ await createTrackedSecret({
environmentSlug: "staging",
workspaceId: seedData1.projectV3.id,
secretPath: testSuitePath,
@@ -186,18 +166,10 @@ describe.each([{ secretPath: "/" }, { secretPath: "/deep" }])(
})
])
);
-
- await deleteSecretV2({
- environmentSlug: "staging",
- workspaceId: seedData1.projectV3.id,
- secretPath: testSuitePath,
- authToken: jwtAuthToken,
- key: "STAGING_KEY"
- });
});
test("Check two level imported secret exist", async () => {
- await createSecretV2({
+ await createTrackedSecret({
environmentSlug: "prod",
workspaceId: seedData1.projectV3.id,
secretPath: testSuitePath,
@@ -236,14 +208,6 @@ describe.each([{ secretPath: "/" }, { secretPath: "/deep" }])(
})
])
);
-
- await deleteSecretV2({
- environmentSlug: "prod",
- workspaceId: seedData1.projectV3.id,
- secretPath: testSuitePath,
- authToken: jwtAuthToken,
- key: "PROD_KEY"
- });
});
},
{ timeout: 60_000 }
@@ -354,7 +318,7 @@ describe.each([{ path: "/" }, { path: "/deep" }])(
});
test("Check imported secret exist", async () => {
- await createSecretV2({
+ await createTrackedSecret({
environmentSlug: "staging",
workspaceId: seedData1.projectV3.id,
secretPath: testSuitePath,
@@ -363,7 +327,7 @@ describe.each([{ path: "/" }, { path: "/deep" }])(
value: "stage-value"
});
- await createSecretV2({
+ await createTrackedSecret({
environmentSlug: "prod",
workspaceId: seedData1.projectV3.id,
secretPath: testSuitePath,
@@ -419,21 +383,6 @@ describe.each([{ path: "/" }, { path: "/deep" }])(
})
])
);
-
- await deleteSecretV2({
- environmentSlug: "staging",
- workspaceId: seedData1.projectV3.id,
- secretPath: testSuitePath,
- authToken: jwtAuthToken,
- key: "STAGING_KEY"
- });
- await deleteSecretV2({
- environmentSlug: "prod",
- workspaceId: seedData1.projectV3.id,
- secretPath: testSuitePath,
- authToken: jwtAuthToken,
- key: "PROD_KEY"
- });
});
},
{ timeout: 60_000 }
diff --git a/backend/e2e-test/routes/v3/secret-recursive.spec.ts b/backend/e2e-test/routes/v3/secret-recursive.spec.ts
index b28dff9854..a6b958599e 100644
--- a/backend/e2e-test/routes/v3/secret-recursive.spec.ts
+++ b/backend/e2e-test/routes/v3/secret-recursive.spec.ts
@@ -12,8 +12,38 @@ describe("Secret Recursive Testing", async () => {
{ name: "deep22", path: "/deep2", expectedSecretCount: 1 }
];
+ // Top-level folder of every fixture path. Deleting these cascades to their
+ // descendants, so they're the only ids cleanup needs.
+ //
+ // Some are created *implicitly*: `createFolder` auto-creates missing parents,
+ // so asking for folder "deep22" at path "/deep2" also creates "/deep2" — and
+ // that id is never returned to us. Deriving roots from the fixture paths
+ // (rather than only recording folders created at "/") is what stops those
+ // from being orphaned in the shared project's prod environment, where this
+ // very spec asserts on exact recursive secret counts.
+ const rootFolderNames = [
+ ...new Set(folderAndSecretNames.map(({ name, path }) => (path === "/" ? name : path.split("/").filter(Boolean)[0])))
+ ];
+
beforeAll(async () => {
const rootFolderIds: string[] = [];
+
+ // Create the implicit roots up front so cleanup has an id for each. Roots a
+ // fixture entry already creates at "/" are skipped — creating them twice
+ // would fail on the duplicate name.
+ const explicitRootNames = new Set(folderAndSecretNames.filter(({ path }) => path === "/").map(({ name }) => name));
+ for (const name of rootFolderNames.filter((n) => !explicitRootNames.has(n))) {
+ // eslint-disable-next-line no-await-in-loop
+ const createdRoot = await createFolder({
+ authToken: jwtAuthToken,
+ environmentSlug: "prod",
+ workspaceId: projectId,
+ secretPath: "/",
+ name
+ });
+ rootFolderIds.push(createdRoot.id);
+ }
+
for (const folder of folderAndSecretNames) {
// eslint-disable-next-line no-await-in-loop
const createdFolder = await createFolder({
@@ -51,13 +81,20 @@ describe("Secret Recursive Testing", async () => {
)
);
- await deleteSecretV2({
- authToken: jwtAuthToken,
- secretPath: "/",
- workspaceId: projectId,
- environmentSlug: "prod",
- key: folderAndSecretNames[0].name
- });
+ // Secrets living at "/" aren't covered by any folder delete above.
+ await Promise.all(
+ folderAndSecretNames
+ .filter(({ path }) => path === "/")
+ .map(({ name }) =>
+ deleteSecretV2({
+ authToken: jwtAuthToken,
+ secretPath: "/",
+ workspaceId: projectId,
+ environmentSlug: "prod",
+ key: name
+ })
+ )
+ );
};
});
diff --git a/backend/e2e-test/routes/v3/secret-reference.spec.ts b/backend/e2e-test/routes/v3/secret-reference.spec.ts
index 7c22b9c843..fbed4ba65e 100644
--- a/backend/e2e-test/routes/v3/secret-reference.spec.ts
+++ b/backend/e2e-test/routes/v3/secret-reference.spec.ts
@@ -1,12 +1,40 @@
import { createFolder, deleteFolder } from "e2e-test/testUtils/folders";
import { createSecretImport, deleteSecretImport } from "e2e-test/testUtils/secret-imports";
-import { createSecretV2, deleteSecretV2, getSecretByNameV2, getSecretsV2 } from "e2e-test/testUtils/secrets";
+import {
+ createSecretV2,
+ deleteSecretV2,
+ getSecretByNameV2,
+ getSecretsV2,
+ waitForReplicatedSecret
+} from "e2e-test/testUtils/secrets";
import { seedData1 } from "@app/db/seed-data";
describe("Secret expansion", () => {
const projectId = seedData1.projectV3.id;
+ const createdSecrets: Parameters<typeof deleteSecretV2>[0][] = [];
+ const createdImports: Parameters<typeof deleteSecretImport>[0][] = [];
+
+ const createTrackedSecret = async (dto: Parameters<typeof createSecretV2>[0]) => {
+ const secret = await createSecretV2(dto);
+ createdSecrets.push(dto);
+ return secret;
+ };
+
+ const createTrackedImport = async (dto: Parameters<typeof createSecretImport>[0]) => {
+ const secretImport = await createSecretImport(dto);
+ createdImports.push({ ...dto, id: secretImport.id });
+ return secretImport;
+ };
+
+ afterEach(async () => {
+ const imports = createdImports.splice(0);
+ const secrets = createdSecrets.splice(0);
+ await Promise.all(imports.map((el) => deleteSecretImport(el)));
+ await Promise.all(secrets.map((el) => deleteSecretV2(el)));
+ });
+
beforeAll(async () => {
const prodRootFolder = await createFolder({
authToken: jwtAuthToken,
@@ -58,7 +86,7 @@ describe("Secret expansion", () => {
for (const secret of secrets) {
// eslint-disable-next-line no-await-in-loop
- await createSecretV2(secret);
+ await createTrackedSecret(secret);
}
const expandedSecret = await getSecretByNameV2({
@@ -84,8 +112,6 @@ describe("Secret expansion", () => {
})
])
);
-
- await Promise.all(secrets.map((el) => deleteSecretV2(el)));
});
test("Local secret reference with empty value", async () => {
@@ -111,7 +137,7 @@ describe("Secret expansion", () => {
for (const secret of secrets) {
// eslint-disable-next-line no-await-in-loop
- await createSecretV2(secret);
+ await createTrackedSecret(secret);
}
const expandedSecret = await getSecretByNameV2({
@@ -137,8 +163,6 @@ describe("Secret expansion", () => {
})
])
);
-
- await Promise.all(secrets.map((el) => deleteSecretV2(el)));
});
test("Local secret reference to non-existent secret keeps literal reference", async () => {
@@ -156,7 +180,7 @@ describe("Secret expansion", () => {
for (const secret of secrets) {
// eslint-disable-next-line no-await-in-loop
- await createSecretV2(secret);
+ await createTrackedSecret(secret);
}
const expandedSecret = await getSecretByNameV2({
@@ -184,8 +208,6 @@ describe("Secret expansion", () => {
})
])
);
-
- await Promise.all(secrets.map((el) => deleteSecretV2(el)));
});
test("Local secret reference with repeated non-existent secret keeps literal references", async () => {
@@ -203,7 +225,7 @@ describe("Secret expansion", () => {
for (const secret of secrets) {
// eslint-disable-next-line no-await-in-loop
- await createSecretV2(secret);
+ await createTrackedSecret(secret);
}
const expandedSecret = await getSecretByNameV2({
@@ -231,8 +253,6 @@ describe("Secret expansion", () => {
})
])
);
-
- await Promise.all(secrets.map((el) => deleteSecretV2(el)));
});
test("Cross environment secret reference", async () => {
@@ -275,7 +295,7 @@ describe("Secret expansion", () => {
for (const secret of secrets) {
// eslint-disable-next-line no-await-in-loop
- await createSecretV2(secret);
+ await createTrackedSecret(secret);
}
const expandedSecret = await getSecretByNameV2({
@@ -301,8 +321,6 @@ describe("Secret expansion", () => {
})
])
);
-
- await Promise.all(secrets.map((el) => deleteSecretV2(el)));
});
test("Non replicated secret import secret expansion on local reference and nested reference", async () => {
@@ -345,10 +363,10 @@ describe("Secret expansion", () => {
for (const secret of secrets) {
// eslint-disable-next-line no-await-in-loop
- await createSecretV2(secret);
+ await createTrackedSecret(secret);
}
- const secretImportFromProdToDev = await createSecretImport({
+ await createTrackedImport({
environmentSlug: seedData1.environment.slug,
workspaceId: projectId,
secretPath: "/",
@@ -381,15 +399,6 @@ describe("Secret expansion", () => {
})
])
);
-
- await Promise.all(secrets.map((el) => deleteSecretV2(el)));
- await deleteSecretImport({
- environmentSlug: seedData1.environment.slug,
- workspaceId: projectId,
- authToken: jwtAuthToken,
- id: secretImportFromProdToDev.id,
- secretPath: "/"
- });
});
test(
@@ -434,10 +443,10 @@ describe("Secret expansion", () => {
for (const secret of secrets) {
// eslint-disable-next-line no-await-in-loop
- await createSecretV2(secret);
+ await createTrackedSecret(secret);
}
- const secretImportFromProdToDev = await createSecretImport({
+ await createTrackedImport({
environmentSlug: seedData1.environment.slug,
workspaceId: projectId,
secretPath: "/",
@@ -447,9 +456,16 @@ describe("Secret expansion", () => {
isReplication: true
});
- // wait for 5 second for replication to finish
- await new Promise((resolve) => {
- setTimeout(resolve, 5000); // time to breathe for db
+ // The replicated import lands asynchronously. Poll for the deepest value
+ // in the chain — NESTED_KEY_2 only reads back expanded once both the
+ // replication and the references it depends on have resolved.
+ await waitForReplicatedSecret({
+ environmentSlug: seedData1.environment.slug,
+ workspaceId: projectId,
+ secretPath: "/",
+ authToken: jwtAuthToken,
+ key: "NESTED_KEY_2",
+ value: "secret reference testing"
});
const listSecrets = await getSecretsV2({
@@ -476,16 +492,7 @@ describe("Secret expansion", () => {
})
])
);
-
- await Promise.all(secrets.map((el) => deleteSecretV2(el)));
- await deleteSecretImport({
- environmentSlug: seedData1.environment.slug,
- workspaceId: projectId,
- authToken: jwtAuthToken,
- id: secretImportFromProdToDev.id,
- secretPath: "/"
- });
},
- { timeout: 10000 }
+ { timeout: 60_000 }
);
});
diff --git a/backend/e2e-test/routes/v3/secrets.spec.ts b/backend/e2e-test/routes/v3/secrets.spec.ts
index db5953f291..bc72140df7 100644
--- a/backend/e2e-test/routes/v3/secrets.spec.ts
+++ b/backend/e2e-test/routes/v3/secrets.spec.ts
@@ -5,6 +5,50 @@ import { crypto } from "@app/lib/crypto/cryptography";
import { initLogger, logger } from "@app/lib/logger";
import { AuthMode } from "@app/services/auth/auth-type";
+// Secrets registered here are torn down after the test that made them. Cleanup
+// used to sit at the end of each test body, so a failing assertion skipped it
+// and left secrets behind in the shared seeded project — which breaks the
+// exact-count assertions in this file (e.g. "List secret raw" expects exactly
+// 5) and any later spec reading the same environment.
+type TCreatedSecret = { path: string; key: string; endpoint: string };
+const createdSecrets: TCreatedSecret[] = [];
+
+// Several tests delete their secret as part of the assertions, so by teardown
+// time there is nothing left — a 404 here means "already gone", not a failure.
+const removeSecretIfPresent = async ({ path, key, endpoint }: TCreatedSecret) => {
+ const res = await testServer.inject({
+ method: "DELETE",
+ url: `${endpoint}/${key}`,
+ headers: {
+ authorization: `Bearer ${jwtAuthToken}`
+ },
+ body: {
+ workspaceId: seedData1.project.id,
+ environment: seedData1.environment.slug,
+ secretPath: path
+ }
+ });
+ if (res.statusCode !== 200 && res.statusCode !== 404) {
+ throw new Error(`cleanup: unexpected ${res.statusCode} deleting "${key}" at "${path}" — ${res.payload}`);
+ }
+};
+
+// Some tests create secrets with a direct or batch inject rather than the
+// helpers below, so they have to register what they made. Call this right after
+// the inject: if the request actually failed, nothing exists and the teardown
+// above no-ops on the 404.
+const trackSecret = (endpoint: string, path: string, ...keys: string[]) => {
+ createdSecrets.push(...keys.map((key) => ({ path, key, endpoint })));
+};
+
+afterEach(async () => {
+ // Dedupe before deleting: a personal override is registered under the same
+ // key as its shared secret, and deleting the shared one removes both. Firing
+ // two concurrent DELETEs for the same secret races into a 500.
+ const unique = new Map(createdSecrets.splice(0).map((el) => [`${el.endpoint}|${el.path}|${el.key}`, el]));
+ await Promise.all([...unique.values()].map(removeSecretIfPresent));
+});
+
const createSecret = async (dto: {
projectKey: string;
path: string;
@@ -31,6 +75,7 @@ const createSecret = async (dto: {
expect(createSecRes.statusCode).toBe(200);
const createdSecretPayload = JSON.parse(createSecRes.payload);
expect(createdSecretPayload).toHaveProperty("secret");
+ createdSecrets.push({ path: dto.path, key: dto.key, endpoint: "/api/v3/secrets" });
return createdSecretPayload.secret;
};
@@ -254,7 +299,6 @@ describe("Secret V3 Router", async () => {
})
])
);
- await deleteSecret({ path, key: secret.key });
});
test.each(secretTestCases)("Get secret by name in path $path", async ({ secret, path }) => {
@@ -279,8 +323,6 @@ describe("Secret V3 Router", async () => {
expect(decryptedSecret.key).toEqual(secret.key);
expect(decryptedSecret.value).toEqual(secret.value);
expect(decryptedSecret.comment).toEqual(secret.comment);
-
- await deleteSecret({ path, key: secret.key });
});
test.each(secretTestCases)(
@@ -343,8 +385,6 @@ describe("Secret V3 Router", async () => {
})
])
);
-
- await deleteSecret({ path, key: secret.key });
});
test.each(secretTestCases)("Update secret in path $path", async ({ path, secret }) => {
@@ -383,8 +423,6 @@ describe("Secret V3 Router", async () => {
})
])
);
-
- await deleteSecret({ path, key: secret.key });
});
test.each(secretTestCases)("Delete secret in path $path", async ({ secret, path }) => {
@@ -429,7 +467,6 @@ describe("Secret V3 Router", async () => {
})
])
);
- await deleteSecret({ path, key: secret.key });
}
);
@@ -450,6 +487,7 @@ describe("Secret V3 Router", async () => {
}))
}
});
+ trackSecret("/api/v3/secrets", path, ...Array.from(Array(5)).map((_e, i) => `BULK-${secret.key}-${i + 1}`));
expect(createSharedSecRes.statusCode).toBe(200);
const createSharedSecPayload = JSON.parse(createSharedSecRes.payload);
expect(createSharedSecPayload).toHaveProperty("secrets");
@@ -466,8 +504,6 @@ describe("Secret V3 Router", async () => {
)
)
);
-
- await Promise.all(Array.from(Array(5)).map((_e, i) => deleteSecret({ path, key: `BULK-${secret.key}-${i + 1}` })));
});
test.each(secretTestCases)("Bulk create fail on existing secret in path $path", async ({ secret, path }) => {
@@ -490,8 +526,6 @@ describe("Secret V3 Router", async () => {
}
});
expect(createSharedSecRes.statusCode).toBe(400);
-
- await deleteSecret({ path, key: `BULK-${secret.key}-1` });
});
test.each(secretTestCases)("Bulk update secrets in path $path", async ({ secret, path }) => {
@@ -534,7 +568,6 @@ describe("Secret V3 Router", async () => {
)
)
);
- await Promise.all(Array.from(Array(5)).map((_e, i) => deleteSecret({ path, key: `BULK-${secret.key}-${i + 1}` })));
});
test.each(secretTestCases)("Bulk delete secrets in path $path", async ({ secret, path }) => {
@@ -605,28 +638,10 @@ const createRawSecret = async (dto: {
expect(createSecRes.statusCode).toBe(200);
const createdSecretPayload = JSON.parse(createSecRes.payload);
expect(createdSecretPayload).toHaveProperty("secret");
+ createdSecrets.push({ path: dto.path, key: dto.key, endpoint: "/api/v3/secrets/raw" });
return createdSecretPayload.secret;
};
-const deleteRawSecret = async (dto: { path: string; key: string }) => {
- const deleteSecRes = await testServer.inject({
- method: "DELETE",
- url: `/api/v3/secrets/raw/${dto.key}`,
- headers: {
- authorization: `Bearer ${jwtAuthToken}`
- },
- body: {
- workspaceId: seedData1.project.id,
- environment: seedData1.environment.slug,
- secretPath: dto.path
- }
- });
- expect(deleteSecRes.statusCode).toBe(200);
- const updatedSecretPayload = JSON.parse(deleteSecRes.payload);
- expect(updatedSecretPayload).toHaveProperty("secret");
- return updatedSecretPayload.secret;
-};
-
// raw secret endpoints
describe.each([{ auth: AuthMode.JWT }, { auth: AuthMode.IDENTITY_ACCESS_TOKEN }])(
"Secret V3 Raw Router - $auth mode",
@@ -817,6 +832,7 @@ describe.each([{ auth: AuthMode.JWT }, { auth: AuthMode.IDENTITY_ACCESS_TOKEN }]
},
body: createSecretReqBody
});
+ trackSecret("/api/v3/secrets/raw", path, secret.key);
expect(createSecRes.statusCode).toBe(200);
const createdSecretPayload = JSON.parse(createSecRes.payload);
expect(createdSecretPayload).toHaveProperty("secret");
@@ -832,8 +848,6 @@ describe.each([{ auth: AuthMode.JWT }, { auth: AuthMode.IDENTITY_ACCESS_TOKEN }]
})
])
);
-
- await deleteRawSecret({ path, key: secret.key });
});
test.each(testRawSecrets)("Get secret by name raw in path $path", async ({ secret, path }) => {
@@ -860,8 +874,6 @@ describe.each([{ auth: AuthMode.JWT }, { auth: AuthMode.IDENTITY_ACCESS_TOKEN }]
secretValue: secret.value
})
);
-
- await deleteRawSecret({ path, key: secret.key });
});
test.each(testRawSecrets)("List secret raw in path $path", async ({ secret, path }) => {
@@ -878,10 +890,6 @@ describe.each([{ auth: AuthMode.JWT }, { auth: AuthMode.IDENTITY_ACCESS_TOKEN }]
)
)
);
-
- await Promise.all(
- Array.from(Array(5)).map((_e, i) => deleteRawSecret({ path, key: `BULK-${secret.key}-${i + 1}` }))
- );
});
test.each(testRawSecrets)("Update secret raw in path $path", async ({ secret, path }) => {
@@ -918,8 +926,6 @@ describe.each([{ auth: AuthMode.JWT }, { auth: AuthMode.IDENTITY_ACCESS_TOKEN }]
})
])
);
-
- await deleteRawSecret({ path, key: secret.key });
});
test.each(testRawSecrets)("Delete secret raw in path $path", async ({ path, secret }) => {
@@ -969,6 +975,7 @@ describe.each([{ auth: AuthMode.JWT }, { auth: AuthMode.IDENTITY_ACCESS_TOKEN }]
},
body: createSecretReqBody
});
+ trackSecret("/api/v3/secrets/raw", path, secret.key);
expect(createSecRes.statusCode).toBe(200);
const createdSecretPayload = JSON.parse(createSecRes.payload);
expect(createdSecretPayload).toHaveProperty("secrets");
@@ -984,8 +991,6 @@ describe.each([{ auth: AuthMode.JWT }, { auth: AuthMode.IDENTITY_ACCESS_TOKEN }]
})
])
);
-
- await deleteRawSecret({ path, key: secret.key });
});
test.each(testRawSecrets)("Bulk update secret raw in path $path", async ({ secret, path }) => {
@@ -1025,8 +1030,6 @@ describe.each([{ auth: AuthMode.JWT }, { auth: AuthMode.IDENTITY_ACCESS_TOKEN }]
})
])
);
-
- await deleteRawSecret({ path, key: secret.key });
});
test.each(testRawSecrets)("Bulk delete secret raw in path $path", async ({ path, secret }) => {
diff --git a/backend/e2e-test/setup/reset-shared-org-flags.ts b/backend/e2e-test/setup/reset-shared-org-flags.ts
new file mode 100644
index 0000000000..4fbee6d55c
--- /dev/null
+++ b/backend/e2e-test/setup/reset-shared-org-flags.ts
@@ -0,0 +1,33 @@
+import type { Knex } from "knex";
+
+import { TableName } from "@app/db/schemas";
+import { seedData1 } from "@app/db/seed-data";
+
+// Several auth specs flip org-wide flags on the *shared* seeded org and undo it
+// in afterAll:
+//
+// auth-mfa.spec.ts enforceMfa
+// auth-signup-sso-enforced.spec authEnforced
+// scim.spec.ts scimEnabled
+// auth-idp-attacks.spec.ts scimEnabled
+//
+// Those afterAll hooks don't run when a file dies hard — a worker OOM or a
+// file-level timeout — and a leaked flag then breaks every later spec that logs
+// in as the seeded user, with a failure that points nowhere near the cause.
+//
+// Test files run sequentially in a single fork, so resetting the flags at the
+// start of every file makes each one self-healing regardless of how its
+// predecessor ended. All three columns default to false in the schema, so this
+// restores the seeded baseline rather than inventing one.
+//
+// This runs before any hook the spec itself registers, so a spec that wants a
+// flag on still gets it. If that ordering ever changed, the affected spec would
+// fail outright rather than silently skip its setup.
+beforeAll(async () => {
+ const db = (globalThis as unknown as { testDb: Knex }).testDb;
+ await db(TableName.Organization).where({ id: seedData1.organization.id }).update({
+ enforceMfa: false,
+ authEnforced: false,
+ scimEnabled: false
+ });
+});
diff --git a/backend/e2e-test/testUtils/secrets.ts b/backend/e2e-test/testUtils/secrets.ts
index 8b9e47f2f1..68e813442c 100644
--- a/backend/e2e-test/testUtils/secrets.ts
+++ b/backend/e2e-test/testUtils/secrets.ts
@@ -128,3 +128,40 @@ export const getSecretsV2 = async (dto: {
}[];
};
};
+
+// Replication and import propagation run asynchronously through BullMQ, so a
+// secret shows up in the destination environment some time after the write.
+// Poll for it instead of sleeping a fixed interval: a fixed wait is at once too
+// short (it flakes whenever CI contention pushes propagation past the deadline)
+// and too long (it burns the whole interval on every pass).
+const REPLICATION_TIMEOUT_MS = 25_000;
+const REPLICATION_POLL_MS = 250;
+
+export const waitForReplicatedSecret = async (dto: {
+ workspaceId: string;
+ environmentSlug: string;
+ secretPath: string;
+ key: string;
+ value: string;
+ authToken: string;
+}) => {
+ const deadline = Date.now() + REPLICATION_TIMEOUT_MS;
+ for (;;) {
+ try {
+ // eslint-disable-next-line no-await-in-loop
+ const secret = await getSecretByNameV2(dto);
+ if (secret.secretValue === dto.value) return secret;
+ } catch {
+ // Not propagated yet — getSecretByNameV2 asserts on a 200.
+ }
+ if (Date.now() >= deadline) {
+ throw new Error(
+ `Timed out after ${REPLICATION_TIMEOUT_MS}ms waiting for "${dto.key}" to reach ${dto.environmentSlug}${dto.secretPath}`
+ );
+ }
+ // eslint-disable-next-line no-await-in-loop
+ await new Promise((resolve) => {
+ setTimeout(resolve, REPLICATION_POLL_MS);
+ });
+ }
+};
diff --git a/backend/vitest.e2e.config.mts b/backend/vitest.e2e.config.mts
index 569a02b1f7..78b0f0a83f 100644
--- a/backend/vitest.e2e.config.mts
+++ b/backend/vitest.e2e.config.mts
@@ -13,6 +13,8 @@ export default defineConfig({
},
environment: "./e2e-test/vitest-environment-knex.ts",
include: ["./e2e-test/**/*.spec.ts"],
+ // Runs per test file, after the environment is up — see the file for why.
+ setupFiles: ["./e2e-test/setup/reset-shared-org-flags.ts"],
pool: "forks",
poolOptions: {
forks: {