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
test(secret-rotation): assert rotation behavior rather than factory calls
Calvinc719df51d43b
diff --git a/backend/e2e-test/fakes/aws-iam-user-secret-rotation-fns.ts b/backend/e2e-test/fakes/aws-iam-user-secret-rotation-fns.tsindex 3358e3ee29..252192d5df 100644--- a/backend/e2e-test/fakes/aws-iam-user-secret-rotation-fns.ts+++ b/backend/e2e-test/fakes/aws-iam-user-secret-rotation-fns.ts@@ -19,6 +19,10 @@ import type * as RealProvider from "../../src/ee/services/secret-rotation-v2/aws// without reaching IAM. Wired up by test.alias in vitest.e2e.config.mts; nothing under src/// references this file.//+// The IAM user itself is not modelled. `parameters.userName` is accepted and ignored, and the+// store starts empty: the first key exists because issueCredentials created it, which is what+// creating a rotation does. A real provider would create the key on that named user.+//// Unlike the Parameter Store fake, this does not mirror one real provider's behaviour. The// provider side of rotation has two shapes, and which one a provider is decides nothing about// the plumbing but everything about what the plumbing has to hand it:@@ -33,30 +37,19 @@ import type * as RealProvider from "../../src/ee/services/secret-rotation-v2/aws// the provider needs is `credentialsToRevoke`. This is datadog-api-key,// azure-client-secret and most API key providers.//-// So the mode is a property of the fake, and the lifecycle spec runs once in each. Both read-// the same two arguments the service computes from `activeIndex`; a provider that got them the-// wrong way round would revoke the credential its users are holding.+// Each mode reacts to a different one of those two arguments, so which credentials are left live+// is enough for a spec to tell what the service handed over. A provider given the two the wrong+// way round would revoke the credential its users are holding, and the key store says so.export enum FakeIamRotationMode {ReplaceInPlace = "replace-in-place",IssueAndDisplace = "issue-and-displace"}-type TFakeCredential = TAwsIamUserSecretRotationGeneratedCredentials[number];--// What the factory was handed, in order. `undefined` is meaningful for credentialsToRevoke (the-// first rotation has no displaced slot), so the field is always present.-export type TFakeIamCall =- | { fn: "issueCredentials" }- | { fn: "rotateCredentials"; credentialsToRevoke: TFakeCredential | undefined; activeCredentials: TFakeCredential }- | { fn: "revokeCredentials"; credentials: TFakeCredential[] }- | { fn: "checkActiveCredentials"; activeCredentials: TFakeCredential };-type TFakeIamState = {mode: FakeIamRotationMode;// The live access keys on the IAM user, by access key ID.keys: Map<string, string>;- calls: TFakeIamCall[];issueError: string | null;afterPersistError: string | null;keySequence: number;@@ -78,7 +71,7 @@ const DEFAULTS = {keySequence: 0};-globalScope.infisicalFakeIamUserSecret ??= { ...DEFAULTS, keys: new Map(), calls: [] };+globalScope.infisicalFakeIamUserSecret ??= { ...DEFAULTS, keys: new Map() };const state = globalScope.infisicalFakeIamUserSecret;@@ -88,7 +81,6 @@ export const fakeIamUserSecret = {reset: () => {Object.assign(state, DEFAULTS);state.keys.clear();- state.calls.length = 0;},// Which of the two provider shapes the factory behaves as. See the comment above.@@ -99,10 +91,6 @@ export const fakeIamUserSecret = {// The access keys that exist on the IAM user right now, as the provider sees them.keys: (): Record<string, string> => Object.fromEntries(state.keys),- // What the service handed the factory, in call order. Lets a spec assert on the slot contract- // rather than only on the credentials that came out of it.- calls: (): TFakeIamCall[] => [...state.calls],-// Make key creation fail, as IAM would for a missing user or a denied policy. Applies to both// issueCredentials and rotateCredentials, since both create a key.failIssueWith: (message: string | null) => {@@ -122,7 +110,7 @@ export const fakeIamUserSecret = {}};-const $createKey = (): TFakeCredential => {+const $createKey = (): TAwsIamUserSecretRotationGeneratedCredentials[number] => {if (state.issueError) throw new BadRequestError({ message: state.issueError });state.keySequence += 1;@@ -152,21 +140,13 @@ export const awsIamUserSecretRotationFactory: TRotationFactory<const issueCredentials: TRotationFactoryIssueCredentials<TAwsIamUserSecretRotationGeneratedCredentials> = async (callback- ) => {- state.calls.push({ fn: "issueCredentials" });-- const credentials = $createKey();-- return callback(credentials);- };+ ) => callback($createKey());const rotateCredentials: TRotationFactoryRotateCredentials<TAwsIamUserSecretRotationGeneratedCredentials> = async (credentialsToRevoke,callback,activeCredentials) => {- state.calls.push({ fn: "rotateCredentials", credentialsToRevoke, activeCredentials });-const credentials = $createKey();if (state.mode === FakeIamRotationMode.ReplaceInPlace) {@@ -188,8 +168,6 @@ export const awsIamUserSecretRotationFactory: TRotationFactory<credentials,callback) => {- state.calls.push({ fn: "revokeCredentials", credentials: [...credentials] });-credentials.forEach(({ accessKeyId }) => $deleteKey(accessKeyId));return callback();@@ -205,8 +183,6 @@ export const awsIamUserSecretRotationFactory: TRotationFactory<const checkActiveCredentials: TRotationFactoryCheckActiveCredentials<TAwsIamUserSecretRotationGeneratedCredentials> = ({ accessKeyId, secretAccessKey }) => {- state.calls.push({ fn: "checkActiveCredentials", activeCredentials: { accessKeyId, secretAccessKey } });-if (state.keys.get(accessKeyId) !== secretAccessKey) {throw new BadRequestError({ message: `Unable to validate credentials: the access key ${accessKeyId} is gone` });}diff --git a/backend/e2e-test/routes/v1/secret-sync.spec.ts b/backend/e2e-test/routes/v1/secret-sync.spec.tsindex bb7f124570..15762f5694 100644--- a/backend/e2e-test/routes/v1/secret-sync.spec.ts+++ b/backend/e2e-test/routes/v1/secret-sync.spec.ts@@ -1,11 +1,10 @@import { randomUUID } from "crypto";import { fakeParameterStore } from "e2e-test/fakes/aws-parameter-store-sync-fns";+import { createAwsAppConnection, deleteAwsAppConnection } from "e2e-test/testUtils/app-connections";import { createFolder, deleteFolder } from "e2e-test/testUtils/folders";import { createSecretImport } from "e2e-test/testUtils/secret-imports";import {- createAwsAppConnection,createSecretSync,- deleteAppConnection,deleteSecretSync,expectDestinationUnchanged,importSecretsForSync,@@ -129,7 +128,7 @@ describe("Secret syncs", async () => {await deleteSecretSync({ syncId, authToken: jwtAuthToken });}- await deleteAppConnection({ connectionId, authToken: jwtAuthToken });+ await deleteAwsAppConnection({ connectionId, authToken: jwtAuthToken });await testServer.inject({method: "DELETE",url: `/api/v1/projects/${projectId}`,diff --git a/backend/e2e-test/routes/v2/secret-rotation.spec.ts b/backend/e2e-test/routes/v2/secret-rotation.spec.tsindex e61356a9dc..a6dc350245 100644--- a/backend/e2e-test/routes/v2/secret-rotation.spec.ts+++ b/backend/e2e-test/routes/v2/secret-rotation.spec.ts@@ -1,5 +1,7 @@import { randomUUID } from "crypto";import { FakeIamRotationMode, fakeIamUserSecret } from "e2e-test/fakes/aws-iam-user-secret-rotation-fns";+import { createAwsAppConnection, deleteAwsAppConnection } from "e2e-test/testUtils/app-connections";+import { createIsolatedOrgAndProject } from "e2e-test/testUtils/fixtures";import { createFolder } from "e2e-test/testUtils/folders";import {checkRotationCredentials,@@ -10,225 +12,203 @@ import {listSecretRotations,rotateSecretRotation} from "e2e-test/testUtils/secret-rotations";-// The AWS app connection helpers live with the secret sync utils, which is where the first specs-// to need them put them.-import { createAwsAppConnection, deleteAppConnection } from "e2e-test/testUtils/secret-syncs";import { createSecretV2, getSecretsV2, updateSecretV2 } from "e2e-test/testUtils/secrets";import { SecretRotationStatus } from "@app/ee/services/secret-rotation-v2/secret-rotation-v2-enums";// What is under test is the rotation plumbing: issuing the first credential, publishing each new-// one into the mapped secrets, which credential the provider is handed to retire, and what+// one into the two mapped secrets, which credential the provider is handed to retire, and what// survives a failure. The provider is AWS IAM user secrets, faked for the whole run// (e2e-test/fakes/aws-iam-user-secret-rotation-fns.ts and the alias block in// vitest.e2e.config.mts), so none of this reaches IAM.//-// The provider side of rotation comes in two shapes, and the service treats both identically:-// it computes an active slot and a displaced slot from activeIndex and hands the factory both.-// The lifecycle rule below therefore runs once per shape, asserting the arguments the factory-// received rather than only the credentials that came back out. A provider that replaces its-// credential in place reads activeCredentials; one that runs two live credentials reads-// credentialsToRevoke. Handing either the wrong one revokes the credential users hold.+// Every assertion is on state a user or an operator could see: the secrets at the path, the keys+// on the IAM user, the rotation's own status. Nothing asserts that the factory was called, or+// with what. The two rotation shapes are covered by running the same lifecycle against a fake in+// each mode, and because each mode retires a different one of the two credentials the service+// offers it, the surviving keys are what say the service offered the right ones.const ENV = "dev";-const MAPPING = { accessKeyId: "AWS_ACCESS_KEY_ID", secretAccessKey: "AWS_SECRET_ACCESS_KEY" };+// The two secret keys the rotation writes its credentials to, which is the whole of what it+// publishes into the project.+const SECRET_KEYS = { accessKeyId: "AWS_ACCESS_KEY_ID", secretAccessKey: "AWS_SECRET_ACCESS_KEY" };// The fake issues keys in order from a counter that resets between tests, so a spec can name the-// credential it expects instead of reading it back out of the fake first.+// credential it expects rather than reading it back out of the fake first. `credential(1)` is the+// one creating the rotation issued, `credential(2)` the one the first rotation issued, and so on.const credential = (sequence: number) => ({accessKeyId: `AKIAFAKE${String(sequence).padStart(4, "0")}`,secretAccessKey: `fake-secret-access-key-${String(sequence).padStart(4, "0")}`});-const mappedSecretsFor = (sequence: number) => ({- [MAPPING.accessKeyId]: credential(sequence).accessKeyId,- [MAPPING.secretAccessKey]: credential(sequence).secretAccessKey+// The mapped secrets as they look when they are holding this credential.+const secretsHolding = (sequence: number) => ({+ [SECRET_KEYS.accessKeyId]: credential(sequence).accessKeyId,+ [SECRET_KEYS.secretAccessKey]: credential(sequence).secretAccessKey});-const keyStoreFor = (...sequences: number[]) =>+// The IAM user's keys when exactly these credentials are live on it.+const liveKeys = (...sequences: number[]) =>Object.fromEntries(sequences.map((sequence) => [credential(sequence).accessKeyId, credential(sequence).secretAccessKey]));describe("Secret rotations", async () => {- // Rotating is synchronous but does a fair amount of KMS work per call, and the lifecycle test- // creates a project, a connection, a rotation and then rotates twice, which is more than the- // 5s default allows for.+ // Rotating is synchronous but does a fair amount of KMS work per call, and a lifecycle test+ // creates an org, a project, a connection and a rotation and then rotates twice, which is more+ // than the 5s default allows for.vi.setConfig({ testTimeout: 30_000, hookTimeout: 30_000 });let projectId: string;let connectionId: string;-- const addSecret = (secretPath: string, key: string, value: string) =>- createSecretV2({ authToken: jwtAuthToken, workspaceId: projectId, environmentSlug: ENV, secretPath, key, value });+ let authToken: string;+ let cleanupOrg: () => Promise<void>;const secretsAt = async (secretPath: string) => {- const { secrets } = await getSecretsV2({- authToken: jwtAuthToken,- workspaceId: projectId,- environmentSlug: ENV,- secretPath- });+ const { secrets } = await getSecretsV2({ authToken, workspaceId: projectId, environmentSlug: ENV, secretPath });return Object.fromEntries(secrets.map((secret) => [secret.secretKey, secret.secretValue]));};- const newRotation = (+ // Creates a rotation at /services with the standard secret keys. The options are the two things+ // tests vary: the keys it publishes to (for the tests about keys already being taken) and the+ // status a refused creation is expected to answer with.+ const newRotation = async (name: string,- overrides: Partial<Parameters<typeof createSecretRotation>[0]> = {},- secretPath = "/services"+ options: {+ secretsMapping?: { accessKeyId: string; secretAccessKey: string };+ secretPath?: string;+ expectStatusCode?: number;+ } = {}) =>createSecretRotation({name,projectId,connectionId,environmentSlug: ENV,- secretPath,- secretsMapping: MAPPING,- authToken: jwtAuthToken,- ...overrides+ secretPath: options.secretPath ?? "/services",+ secretsMapping: options.secretsMapping ?? SECRET_KEYS,+ expectStatusCode: options.expectStatusCode,+ authToken});- // Everything a test touches is built here and torn down after it. An app connection is- // org-scoped rather than project-scoped, so sharing one would leave a single row that every- // test's rotations hang off, and a rotation left behind in the seeded project would be picked- // up by the rotation cron, which under NODE_ENV=test treats every auto-enabled rotation as due- // and runs it inline once a minute.+ // A fresh org and project per test, so no test can be reached by another's writes or teardown.+ // An app connection is org-scoped rather than project-scoped, so sharing one would leave a+ // single row every test's rotations hang off. A rotation left behind in a shared org would also+ // be picked up by the rotation cron, which under NODE_ENV=test treats every auto-enabled+ // rotation as due and runs it inline once a minute.beforeEach(async () => {fakeIamUserSecret.reset();- const suffix = randomUUID().slice(0, 8);-- const projectRes = await testServer.inject({- method: "POST",- url: "/api/v1/projects",- headers: { authorization: `Bearer ${jwtAuthToken}` },- body: { projectName: `secret-rotation-e2e-${suffix}` }- });- expect(projectRes.statusCode).toBe(200);- projectId = projectRes.json().project.id as string;+ ({ projectId, authToken, cleanup: cleanupOrg } = await createIsolatedOrgAndProject("secret-rotation-e2e"));connectionId = await createAwsAppConnection({- name: `secret-rotation-e2e-${suffix}`,- authToken: jwtAuthToken+ name: `secret-rotation-e2e-${randomUUID().slice(0, 8)}`,+ authToken});- await createFolder({- authToken: jwtAuthToken,- workspaceId: projectId,- environmentSlug: ENV,- secretPath: "/",- name: "services"- });+ await createFolder({ authToken, workspaceId: projectId, environmentSlug: ENV, secretPath: "/", name: "services" });});afterEach(async () => {- // Order matters. A rotation holds a foreign key to the connection, and deleting a project- // only soft deletes it, leaving the rotation rows in place, so the connection delete would- // fail on the constraint if the rotations went second. Whatever each test left is read back- // from the project rather than tracked, so a test that deletes its own rotation needs no- // bookkeeping here. Neither flag is set: the secrets go with the project and the fake's keys- // go with the reset.- const rotations = await listSecretRotations({ projectId, authToken: jwtAuthToken });+ // Order matters. A rotation holds a foreign key to the connection, so the connection delete+ // fails on the constraint while any rotation is still pointing at it. Whatever each test left+ // is read back from the project rather than tracked, so a test that deletes its own rotation+ // needs no bookkeeping here. Neither flag is set: the secrets go with the org, and the fake's+ // keys go with the reset.+ const rotations = await listSecretRotations({ projectId, authToken });for (const rotation of rotations) {// eslint-disable-next-line no-await-in-loopawait deleteSecretRotation({rotationId: rotation.id,deleteSecrets: false,revokeGeneratedCredentials: false,- authToken: jwtAuthToken+ authToken});}- await deleteAppConnection({ connectionId, authToken: jwtAuthToken });- await testServer.inject({- method: "DELETE",- url: `/api/v1/projects/${projectId}`,- headers: { authorization: `Bearer ${jwtAuthToken}` }+ await deleteAwsAppConnection({ connectionId, authToken });+ await cleanupOrg();+ });++ describe("Creating a rotation issues the first credential and publishes it", () => {+ test("The mapped secrets hold the issued credential and the provider has one live key", async () => {+ const { secretRotation } = await newRotation("publishes-first-credential");++ expect(await secretsAt("/services")).toEqual(secretsHolding(1));+ expect(fakeIamUserSecret.keys()).toEqual(liveKeys(1));+ expect(secretRotation!.activeIndex).toBe(0);+ expect(secretRotation!.rotationStatus).toBe(SecretRotationStatus.Success);+ // Auto rotation is off, so there is nothing for the cron to pick up:+ // findSecretRotationsToQueue gates on this being set as well as on isAutoRotationEnabled.+ expect(secretRotation!.nextRotationAt).toBeNull();});});+ // The two provider shapes. Both rotate through the same service call and both are handed the+ // same two credentials; they differ in which one they retire, so the keys left live are what+ // show the service handed over the right ones. Getting them the wrong way round would revoke+ // the credential the mapped secrets are publishing.describe("A rotation publishes the new credential and offers the provider the one it displaces", () => {- test.each([- {- mode: FakeIamRotationMode.ReplaceInPlace,- // Publishing kills the previous credential, so only ever one key exists.- afterFirstRotation: keyStoreFor(2),- afterSecondRotation: keyStoreFor(3)- },- {- mode: FakeIamRotationMode.IssueAndDisplace,- // The previous credential stays usable, and the one before it is the one retired.- afterFirstRotation: keyStoreFor(1, 2),- afterSecondRotation: keyStoreFor(2, 3)- }- ])(- "A $mode provider is handed the active and displaced credentials across a create, two rotations and a delete",- async ({ mode, afterFirstRotation, afterSecondRotation }) => {- fakeIamUserSecret.setMode(mode);-- const { secretRotation } = await newRotation("lifecycle");- const rotationId = secretRotation!.id;-- // Creation issues the first credential and writes it to the two mapped keys.- expect(fakeIamUserSecret.calls()).toEqual([{ fn: "issueCredentials" }]);- expect(fakeIamUserSecret.keys()).toEqual(keyStoreFor(1));- expect(await secretsAt("/services")).toEqual(mappedSecretsFor(1));- expect(secretRotation!.activeIndex).toBe(0);- // Auto rotation is off, so there is nothing for the cron to pick up. findSecretRotationsToQueue- // gates on both this and isAutoRotationEnabled.- expect(secretRotation!.nextRotationAt).toBeNull();-- const first = await rotateSecretRotation({ rotationId, authToken: jwtAuthToken });-- expect(first.secretRotation!.activeIndex).toBe(1);- expect(first.secretRotation!.rotationStatus).toBe(SecretRotationStatus.Success);- expect(await secretsAt("/services")).toEqual(mappedSecretsFor(2));- expect(fakeIamUserSecret.keys()).toEqual(afterFirstRotation);- // Nothing is displaced on the first rotation: only one slot has ever been filled.- expect(fakeIamUserSecret.calls().at(-1)).toEqual({- fn: "rotateCredentials",- credentialsToRevoke: undefined,- activeCredentials: credential(1)- });-- const second = await rotateSecretRotation({ rotationId, authToken: jwtAuthToken });-- expect(second.secretRotation!.activeIndex).toBe(0);- expect(await secretsAt("/services")).toEqual(mappedSecretsFor(3));- expect(fakeIamUserSecret.keys()).toEqual(afterSecondRotation);- // The displaced credential is the one from two rotations ago, never the one the mapped- // secrets are currently holding.- expect(fakeIamUserSecret.calls().at(-1)).toEqual({- fn: "rotateCredentials",- credentialsToRevoke: credential(1),- activeCredentials: credential(2)- });-- // Two slots, newest in the slot activeIndex names.- expect(await getGeneratedCredentials({ rotationId, authToken: jwtAuthToken })).toEqual({- generatedCredentials: [credential(3), credential(2)],- activeIndex: 0- });-- await deleteSecretRotation({- rotationId,- deleteSecrets: true,- revokeGeneratedCredentials: true,- authToken: jwtAuthToken- });-- // Both slots are offered for revocation, in slot order, including the one a- // replace-in-place provider already retired.- expect(fakeIamUserSecret.calls().at(-1)).toEqual({- fn: "revokeCredentials",- credentials: [credential(3), credential(2)]- });- expect(fakeIamUserSecret.keys()).toEqual({});- expect(await secretsAt("/services")).toEqual({});- expect(await listSecretRotations({ projectId, authToken: jwtAuthToken })).toEqual([]);- }- );+ test("A provider that replaces its credential in place is left with only the published one", async () => {+ fakeIamUserSecret.setMode(FakeIamRotationMode.ReplaceInPlace);++ const { secretRotation } = await newRotation("replace-in-place");+ const rotationId = secretRotation!.id;++ // The provider retires the credential it was told is active, which is the one the mapped+ // secrets were publishing until this call. Its predecessor is long dead.+ const first = await rotateSecretRotation({ rotationId, authToken });++ expect(await secretsAt("/services")).toEqual(secretsHolding(2));+ expect(fakeIamUserSecret.keys()).toEqual(liveKeys(2));+ expect(first.secretRotation!.activeIndex).toBe(1);+ expect(first.secretRotation!.rotationStatus).toBe(SecretRotationStatus.Success);+ expect(first.secretRotation!.nextRotationAt).toBeNull();++ const second = await rotateSecretRotation({ rotationId, authToken });++ expect(await secretsAt("/services")).toEqual(secretsHolding(3));+ expect(fakeIamUserSecret.keys()).toEqual(liveKeys(3));+ // Back to the first slot: two slots, alternating.+ expect(second.secretRotation!.activeIndex).toBe(0);+ });++ test("A provider that runs two credentials keeps the previous one live and retires the one before it", async () => {+ fakeIamUserSecret.setMode(FakeIamRotationMode.IssueAndDisplace);++ const { secretRotation } = await newRotation("issue-and-displace");+ const rotationId = secretRotation!.id;++ // Nothing is displaced on the first rotation, because only one slot has ever been filled,+ // so the credential creating the rotation issued stays live alongside the new one.+ const first = await rotateSecretRotation({ rotationId, authToken });++ expect(await secretsAt("/services")).toEqual(secretsHolding(2));+ expect(fakeIamUserSecret.keys()).toEqual(liveKeys(1, 2));+ expect(first.secretRotation!.activeIndex).toBe(1);++ // The second rotation displaces the first credential, never the one the mapped secrets are+ // publishing.+ const second = await rotateSecretRotation({ rotationId, authToken });++ expect(await secretsAt("/services")).toEqual(secretsHolding(3));+ expect(fakeIamUserSecret.keys()).toEqual(liveKeys(2, 3));+ expect(second.secretRotation!.activeIndex).toBe(0);+ });++ test("Both credentials are readable, newest in the slot the active index names", async () => {+ const { secretRotation } = await newRotation("generated-credentials");+ const rotationId = secretRotation!.id;++ await rotateSecretRotation({ rotationId, authToken });+ await rotateSecretRotation({ rotationId, authToken });++ expect(await getGeneratedCredentials({ rotationId, authToken })).toEqual({+ generatedCredentials: [credential(3), credential(2)],+ activeIndex: 0+ });+ });});describe("A rotation that cannot issue a credential changes nothing", () => {@@ -240,7 +220,7 @@ describe("Secret rotations", async () => {expect(error!.message).toContain("IAM denied CreateAccessKey");expect(fakeIamUserSecret.keys()).toEqual({});expect(await secretsAt("/services")).toEqual({});- expect(await listSecretRotations({ projectId, authToken: jwtAuthToken })).toEqual([]);+ expect(await listSecretRotations({ projectId, authToken })).toEqual([]);});test("A provider that refuses a later credential leaves the working one published", async () => {@@ -251,14 +231,14 @@ describe("Secret rotations", async () => {// A provider failure answers 500 rather than 4xx: rotateSecretRotation wraps whatever// rotateGeneratedCredentials threw in an InternalServerError.- const { error } = await rotateSecretRotation({ rotationId, authToken: jwtAuthToken, expectStatusCode: 500 });+ const { error } = await rotateSecretRotation({ rotationId, authToken, expectStatusCode: 500 });expect(error!.message).toContain("IAM throttled CreateAccessKey");// The credential users hold is untouched, at the provider and in the mapped secrets.- expect(fakeIamUserSecret.keys()).toEqual(keyStoreFor(1));- expect(await secretsAt("/services")).toEqual(mappedSecretsFor(1));+ expect(fakeIamUserSecret.keys()).toEqual(liveKeys(1));+ expect(await secretsAt("/services")).toEqual(secretsHolding(1));- const failed = await getSecretRotation({ rotationId, authToken: jwtAuthToken });+ const failed = await getSecretRotation({ rotationId, authToken });expect(failed.rotationStatus).toBe(SecretRotationStatus.Failed);expect(failed.lastRotationMessage).toContain("IAM throttled CreateAccessKey");expect(failed.activeIndex).toBe(0);@@ -270,48 +250,63 @@ describe("Secret rotations", async () => {fakeIamUserSecret.failAfterPersistWith("IAM denied DeleteAccessKey");- const { error } = await rotateSecretRotation({ rotationId, authToken: jwtAuthToken, expectStatusCode: 500 });+ const { error } = await rotateSecretRotation({ rotationId, authToken, expectStatusCode: 500 });expect(error!.message).toContain("IAM denied DeleteAccessKey");// The write half of the rotation committed before the provider threw, so the new credential// is live and published while the rotation reports failed. A provider that retires the// displaced credential after publishing rather than before lands here.- expect(await secretsAt("/services")).toEqual(mappedSecretsFor(2));- const failed = await getSecretRotation({ rotationId, authToken: jwtAuthToken });+ expect(await secretsAt("/services")).toEqual(secretsHolding(2));++ const failed = await getSecretRotation({ rotationId, authToken });expect(failed.activeIndex).toBe(1);expect(failed.rotationStatus).toBe(SecretRotationStatus.Failed);});});describe("A rotation is created against one free set of secret keys at one existing secret path", () => {- test("Creating a rotation is refused when the name, the mapped keys or the secret path do not allow it", async () => {+ test("Creating a rotation is refused when the name is already used at the path", async () => {await newRotation("taken-name");- const sameName = await newRotation("taken-name", {+ const { error } = await newRotation("taken-name", {// Different keys, so this can only fail on the name.secretsMapping: { accessKeyId: "OTHER_ACCESS_KEY_ID", secretAccessKey: "OTHER_SECRET_ACCESS_KEY" },expectStatusCode: 400});- expect(sameName.error!.message).toContain("taken-name");- expect(sameName.error!.message).toContain("/services");- await addSecret("/services", "HAND_WRITTEN_KEY", "hand-written-value");- const takenKey = await newRotation("taken-key", {+ expect(error!.message).toContain("taken-name");+ expect(error!.message).toContain("/services");+ expect(await listSecretRotations({ projectId, authToken })).toHaveLength(1);+ });++ test("Creating a rotation is refused when a mapped secret key already exists", async () => {+ await createSecretV2({+ authToken,+ workspaceId: projectId,+ environmentSlug: ENV,+ secretPath: "/services",+ key: "HAND_WRITTEN_KEY",+ value: "hand-written-value"+ });++ const { error } = await newRotation("taken-key", {secretsMapping: { accessKeyId: "HAND_WRITTEN_KEY", secretAccessKey: "OTHER_SECRET_ACCESS_KEY" },expectStatusCode: 400});- expect(takenKey.error!.message).toContain("HAND_WRITTEN_KEY");- const missingPath = await newRotation("missing-path", { expectStatusCode: 400 }, "/does/not/exist");- expect(missingPath.error!.message).toContain("/does/not/exist");- expect(missingPath.error!.message).toContain(ENV);+ expect(error!.message).toContain("HAND_WRITTEN_KEY");+ // The hand-written secret is still its own, and no credential was issued for a rotation+ // that was refused before it reached the provider.+ expect(await secretsAt("/services")).toEqual({ HAND_WRITTEN_KEY: "hand-written-value" });+ expect(fakeIamUserSecret.keys()).toEqual({});+ });- // Only the first rotation was created, and the hand-written secret is still its own.- expect(await listSecretRotations({ projectId, authToken: jwtAuthToken })).toHaveLength(1);- expect(await secretsAt("/services")).toEqual({- ...mappedSecretsFor(1),- HAND_WRITTEN_KEY: "hand-written-value"- });+ test("Creating a rotation is refused when the secret path does not exist", async () => {+ const { error } = await newRotation("missing-path", { secretPath: "/does/not/exist", expectStatusCode: 400 });++ expect(error!.message).toContain("/does/not/exist");+ expect(error!.message).toContain(ENV);+ expect(fakeIamUserSecret.keys()).toEqual({});});});@@ -323,43 +318,57 @@ describe("Secret rotations", async () => {workspaceId: projectId,environmentSlug: ENV,secretPath: "/services",- key: MAPPING.accessKeyId,+ key: SECRET_KEYS.accessKeyId,value: "hand-written-value",- authToken: jwtAuthToken,+ authToken,expectStatusCode: 400});expect(error!.message).toContain("Cannot update rotated secret");- expect(await secretsAt("/services")).toEqual(mappedSecretsFor(1));+ expect(await secretsAt("/services")).toEqual(secretsHolding(1));+ });++ test("Deleting a rotation with both flags set revokes the credentials and removes the secrets", async () => {+ const { secretRotation } = await newRotation("deletes-everything");+ const rotationId = secretRotation!.id;++ await rotateSecretRotation({ rotationId, authToken });++ await deleteSecretRotation({ rotationId, deleteSecrets: true, revokeGeneratedCredentials: true, authToken });++ // Both slots are revoked, not just the published one, so the previous credential cannot+ // outlive the rotation that issued it.+ expect(fakeIamUserSecret.keys()).toEqual({});+ expect(await secretsAt("/services")).toEqual({});+ expect(await listSecretRotations({ projectId, authToken })).toEqual([]);});- test("Deleting a rotation without revoking or deleting leaves the credential live and the secrets editable", async () => {+ test("Deleting a rotation with neither flag set leaves the credential live and the secrets editable", async () => {const { secretRotation } = await newRotation("leaves-everything");await deleteSecretRotation({rotationId: secretRotation!.id,deleteSecrets: false,revokeGeneratedCredentials: false,- authToken: jwtAuthToken+ authToken});// The provider was never asked to revoke anything, so the credential still works. This is// the escape hatch for a rotation whose credential is in use elsewhere.- expect(fakeIamUserSecret.calls().some((call) => call.fn === "revokeCredentials")).toBe(false);- expect(fakeIamUserSecret.keys()).toEqual(keyStoreFor(1));- expect(await secretsAt("/services")).toEqual(mappedSecretsFor(1));+ expect(fakeIamUserSecret.keys()).toEqual(liveKeys(1));+ expect(await secretsAt("/services")).toEqual(secretsHolding(1));- // Nothing owns the secrets now, so the write the previous test was refused succeeds.+ // Nothing owns the secrets now, so the write the rotation refused above succeeds.await updateSecretV2({workspaceId: projectId,environmentSlug: ENV,secretPath: "/services",- key: MAPPING.accessKeyId,+ key: SECRET_KEYS.accessKeyId,value: "hand-written-value",- authToken: jwtAuthToken+ authToken});- expect((await secretsAt("/services"))[MAPPING.accessKeyId]).toBe("hand-written-value");+ expect((await secretsAt("/services"))[SECRET_KEYS.accessKeyId]).toBe("hand-written-value");});});@@ -368,15 +377,15 @@ describe("Secret rotations", async () => {const { secretRotation } = await newRotation("check-credentials");const rotationId = secretRotation!.id;- await checkRotationCredentials({ rotationId, authToken: jwtAuthToken });+ await checkRotationCredentials({ rotationId, authToken });fakeIamUserSecret.revokeOutOfBand(credential(1).accessKeyId);- const error = await checkRotationCredentials({ rotationId, authToken: jwtAuthToken, expectStatusCode: 400 });+ const error = await checkRotationCredentials({ rotationId, authToken, expectStatusCode: 400 });expect(error!.message).toContain(credential(1).accessKeyId);// The check reports, it does not repair: the rotation still holds the dead credential.- expect(await secretsAt("/services")).toEqual(mappedSecretsFor(1));+ expect(await secretsAt("/services")).toEqual(secretsHolding(1));});});});diff --git a/backend/e2e-test/testUtils/app-connections.ts b/backend/e2e-test/testUtils/app-connections.tsnew file mode 100644index 0000000000..6ae72946fe--- /dev/null+++ b/backend/e2e-test/testUtils/app-connections.ts@@ -0,0 +1,35 @@+// An app connection is org-scoped and shared by every feature that reaches a third party, so the+// helpers live here rather than with the first feature that needed one. Names carry the app: the+// route, the credential shape and the response are all per-app.+//+// The AWS connection is faked for the whole e2e run (e2e-test/fakes/aws-connection-fns.ts and the+// alias block in vitest.e2e.config.mts), so these credentials are never validated against AWS.++export const createAwsAppConnection = async (dto: { name: string; authToken: string }) => {+ const res = await testServer.inject({+ method: "POST",+ url: `/api/v1/app-connections/aws`,+ headers: { authorization: `Bearer ${dto.authToken}` },+ body: {+ name: dto.name,+ method: "access-key",+ credentials: {+ accessKeyId: "AKIAFAKEACCESSKEYID",+ secretAccessKey: "fake-secret-access-key"+ }+ }+ });++ expect(res.statusCode).toBe(200);+ return res.json().appConnection.id as string;+};++export const deleteAwsAppConnection = async (dto: { connectionId: string; authToken: string }) => {+ const res = await testServer.inject({+ method: "DELETE",+ url: `/api/v1/app-connections/aws/${dto.connectionId}`,+ headers: { authorization: `Bearer ${dto.authToken}` }+ });++ expect(res.statusCode).toBe(200);+};diff --git a/backend/e2e-test/testUtils/fixtures.ts b/backend/e2e-test/testUtils/fixtures.tsnew file mode 100644index 0000000000..8ed20c9281--- /dev/null+++ b/backend/e2e-test/testUtils/fixtures.ts@@ -0,0 +1,49 @@+import { randomUUID } from "node:crypto";++import { selectOrg } from "./auth";++// Full isolation per test: a fresh org and project rather than a fresh project inside the shared+// seeded org. Org-scoped state (roles, membership) can't leak between tests either this way, not+// just project-scoped state. Cheaper alternatives exist (see secret-sync.spec.ts's beforeEach,+// which only creates a fresh project under the shared seeded org) but this is the one to reach for+// by default going forward.+export const createIsolatedOrgAndProject = async (namePrefix: string) => {+ const name = `${namePrefix}-${randomUUID().slice(0, 8)}`;++ const orgRes = await testServer.inject({+ method: "POST",+ url: "/api/v2/organizations",+ headers: { authorization: `Bearer ${jwtAuthToken}` },+ body: { name }+ });+ expect(orgRes.statusCode).toBe(200);+ const orgId = orgRes.json().organization.id as string;++ // The org creation token is scoped to whatever org it already carried; project creation reads+ // its org from the token too (project-router.ts), so a token scoped to the new org is required+ // before anything project-shaped can be created in it.+ const selectOrgRes = await selectOrg(jwtAuthToken, orgId);+ expect(selectOrgRes.statusCode).toBe(200);+ const authToken = selectOrgRes.payload.token as string;++ const projectRes = await testServer.inject({+ method: "POST",+ url: "/api/v1/projects",+ headers: { authorization: `Bearer ${authToken}` },+ body: { projectName: name }+ });+ expect(projectRes.statusCode).toBe(200);+ const projectId = projectRes.json().project.id as string;++ // Hard-deletes the org row; every project/environment/secret/webhook underneath it is reaped by+ // FK cascade (org-service.ts:deleteOrganizationById), so there's nothing else to tear down.+ const cleanup = async () => {+ await testServer.inject({+ method: "DELETE",+ url: `/api/v2/organizations/${orgId}`,+ headers: { authorization: `Bearer ${authToken}` }+ });+ };++ return { orgId, projectId, authToken, cleanup };+};diff --git a/backend/e2e-test/testUtils/secret-syncs.ts b/backend/e2e-test/testUtils/secret-syncs.tsindex c980e31f8d..432cdbeb6b 100644--- a/backend/e2e-test/testUtils/secret-syncs.ts+++ b/backend/e2e-test/testUtils/secret-syncs.ts@@ -24,35 +24,6 @@ type TSecretSyncRecord = {const TERMINAL_STATUSES: string[] = [SecretSyncStatus.Succeeded, SecretSyncStatus.Failed];-export const createAwsAppConnection = async (dto: { name: string; authToken: string }) => {- const res = await testServer.inject({- method: "POST",- url: `/api/v1/app-connections/aws`,- headers: { authorization: `Bearer ${dto.authToken}` },- body: {- name: dto.name,- method: "access-key",- credentials: {- accessKeyId: "AKIAFAKEACCESSKEYID",- secretAccessKey: "fake-secret-access-key"- }- }- });-- expect(res.statusCode).toBe(200);- return res.json().appConnection.id as string;-};--export const deleteAppConnection = async (dto: { connectionId: string; authToken: string }) => {- const res = await testServer.inject({- method: "DELETE",- url: `/api/v1/app-connections/aws/${dto.connectionId}`,- headers: { authorization: `Bearer ${dto.authToken}` }- });-- expect(res.statusCode).toBe(200);-};-export const createSecretSync = async (dto: {name: string;projectId: string;