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): cover the rotation plumbing with a faked provider
Calvin403cb6fc2f9e
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.tsnew file mode 100644index 0000000000..3358e3ee29--- /dev/null+++ b/backend/e2e-test/fakes/aws-iam-user-secret-rotation-fns.ts@@ -0,0 +1,231 @@+import {+ TAwsIamUserSecretRotationGeneratedCredentials,+ TAwsIamUserSecretRotationWithConnection+} from "@app/ee/services/secret-rotation-v2/aws-iam-user-secret";+import {+ TRotationFactory,+ TRotationFactoryCheckActiveCredentials,+ TRotationFactoryGetSecretsPayload,+ TRotationFactoryIssueCredentials,+ TRotationFactoryRevokeCredentials,+ TRotationFactoryRotateCredentials+} from "@app/ee/services/secret-rotation-v2/secret-rotation-v2-types";+import { BadRequestError } from "@app/lib/errors";++// Type-only, and by a path the aliases do not match, so this does not resolve back to here.+import type * as RealProvider from "../../src/ee/services/secret-rotation-v2/aws-iam-user-secret/aws-iam-user-secret-rotation-fns";++// Stands in for the AWS IAM user secret provider so the specs can drive the rotation plumbing+// without reaching IAM. Wired up by test.alias in vitest.e2e.config.mts; nothing under src/+// references this file.+//+// 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:+//+// replace-in-place one live credential. Publishing the new one kills the old immediately,+// so `credentialsToRevoke` names a credential that is already dead. What+// the provider needs is `activeCredentials`, to authenticate as itself.+// This is ldap-password, unix-linux, windows and hp-ilo.+//+// issue-and-displace two live credentials. The new one is published while the previous stays+// usable, and the credential two rotations back is the one retired. What+// 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.++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;+};++// 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 service's+// relative import, a spec through its own path), and the bundler then instantiates it twice:+// the rotation writes to one copy while the spec reads an empty other one, and the only symptom+// is an assertion that never comes true. Same reasoning as the AWS sync fakes.+const globalScope = globalThis as typeof globalThis & {+ infisicalFakeIamUserSecret?: TFakeIamState;+};++const DEFAULTS = {+ mode: FakeIamRotationMode.IssueAndDisplace,+ issueError: null,+ afterPersistError: null,+ keySequence: 0+};++globalScope.infisicalFakeIamUserSecret ??= { ...DEFAULTS, keys: new Map(), calls: [] };++const state = globalScope.infisicalFakeIamUserSecret;++// Behavior a spec can change. Everything resets between test files, so a spec never inherits+// another's state or configuration. See e2e-test/setup/reset-fakes.ts.+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.+ setMode: (mode: FakeIamRotationMode) => {+ state.mode = mode;+ },++ // 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) => {+ state.issueError = message;+ },++ // Make the factory throw *after* the callback has committed the new credentials. A provider+ // that retires the displaced key after publishing the new one, rather than before, fails here+ // when that retirement fails, with the rotation already persisted.+ failAfterPersistWith: (message: string | null) => {+ state.afterPersistError = message;+ },++ // Delete a key behind Infisical's back, as an operator revoking it in the AWS console would.+ revokeOutOfBand: (accessKeyId: string) => {+ state.keys.delete(accessKeyId);+ }+};++const $createKey = (): TFakeCredential => {+ if (state.issueError) throw new BadRequestError({ message: state.issueError });++ state.keySequence += 1;+ const sequence = String(state.keySequence).padStart(4, "0");+ const credential = {+ accessKeyId: `AKIAFAKE${sequence}`,+ secretAccessKey: `fake-secret-access-key-${sequence}`+ };++ state.keys.set(credential.accessKeyId, credential.secretAccessKey);++ return credential;+};++// IAM answers a delete for a key that is already gone with 404, which the real providers treat+// as success since revocation is the desired end state. That matters in replace-in-place mode,+// where the credential the service offers for revocation died when the next one was published.+const $deleteKey = (accessKeyId: string) => {+ state.keys.delete(accessKeyId);+};++export const awsIamUserSecretRotationFactory: TRotationFactory<+ TAwsIamUserSecretRotationWithConnection,+ TAwsIamUserSecretRotationGeneratedCredentials+> = (secretRotation) => {+ const { secretsMapping } = secretRotation;++ const issueCredentials: TRotationFactoryIssueCredentials<TAwsIamUserSecretRotationGeneratedCredentials> = async (+ callback+ ) => {+ state.calls.push({ fn: "issueCredentials" });++ const credentials = $createKey();++ return callback(credentials);+ };++ const rotateCredentials: TRotationFactoryRotateCredentials<TAwsIamUserSecretRotationGeneratedCredentials> = async (+ credentialsToRevoke,+ callback,+ activeCredentials+ ) => {+ state.calls.push({ fn: "rotateCredentials", credentialsToRevoke, activeCredentials });++ const credentials = $createKey();++ if (state.mode === FakeIamRotationMode.ReplaceInPlace) {+ // The credential being published replaces the live one, so the credential users hold stops+ // working the moment this returns. Nothing is left to retire later.+ $deleteKey(activeCredentials.accessKeyId);+ } else if (credentialsToRevoke) {+ $deleteKey(credentialsToRevoke.accessKeyId);+ }++ const rotation = await callback(credentials);++ if (state.afterPersistError) throw new BadRequestError({ message: state.afterPersistError });++ return rotation;+ };++ const revokeCredentials: TRotationFactoryRevokeCredentials<TAwsIamUserSecretRotationGeneratedCredentials> = async (+ credentials,+ callback+ ) => {+ state.calls.push({ fn: "revokeCredentials", credentials: [...credentials] });++ credentials.forEach(({ accessKeyId }) => $deleteKey(accessKeyId));++ return callback();+ };++ const getSecretsPayload: TRotationFactoryGetSecretsPayload<TAwsIamUserSecretRotationGeneratedCredentials> = (+ credentials+ ) => [+ { key: secretsMapping.accessKeyId, value: credentials.accessKeyId },+ { key: secretsMapping.secretAccessKey, value: credentials.secretAccessKey }+ ];++ 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` });+ }++ return Promise.resolve();+ };++ return {+ issueCredentials,+ revokeCredentials,+ rotateCredentials,+ getSecretsPayload,+ checkActiveCredentials+ };+};++// Nothing forces a module replaced by an alias to match the module it replaces, so a signature+// change in the real provider would otherwise leave this fake quietly wrong. This assignment+// fails type-checking instead.+export const assertFakeMatchesRealProvider: Pick<typeof RealProvider, "awsIamUserSecretRotationFactory"> = {+ awsIamUserSecretRotationFactory+};diff --git a/backend/e2e-test/routes/v2/secret-rotation.spec.ts b/backend/e2e-test/routes/v2/secret-rotation.spec.tsnew file mode 100644index 0000000000..e61356a9dc--- /dev/null+++ b/backend/e2e-test/routes/v2/secret-rotation.spec.ts@@ -0,0 +1,382 @@+import { randomUUID } from "crypto";+import { FakeIamRotationMode, fakeIamUserSecret } from "e2e-test/fakes/aws-iam-user-secret-rotation-fns";+import { createFolder } from "e2e-test/testUtils/folders";+import {+ checkRotationCredentials,+ createSecretRotation,+ deleteSecretRotation,+ getGeneratedCredentials,+ getSecretRotation,+ 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+// 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.++const ENV = "dev";++const MAPPING = { 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.+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+});++const keyStoreFor = (...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.+ 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 });++ const secretsAt = async (secretPath: string) => {+ const { secrets } = await getSecretsV2({+ authToken: jwtAuthToken,+ workspaceId: projectId,+ environmentSlug: ENV,+ secretPath+ });+ return Object.fromEntries(secrets.map((secret) => [secret.secretKey, secret.secretValue]));+ };++ const newRotation = (+ name: string,+ overrides: Partial<Parameters<typeof createSecretRotation>[0]> = {},+ secretPath = "/services"+ ) =>+ createSecretRotation({+ name,+ projectId,+ connectionId,+ environmentSlug: ENV,+ secretPath,+ secretsMapping: MAPPING,+ authToken: jwtAuthToken,+ ...overrides+ });++ // 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.+ 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;++ connectionId = await createAwsAppConnection({+ name: `secret-rotation-e2e-${suffix}`,+ authToken: jwtAuthToken+ });++ await createFolder({+ authToken: jwtAuthToken,+ 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 });+ for (const rotation of rotations) {+ // eslint-disable-next-line no-await-in-loop+ await deleteSecretRotation({+ rotationId: rotation.id,+ deleteSecrets: false,+ revokeGeneratedCredentials: false,+ authToken: jwtAuthToken+ });+ }++ await deleteAppConnection({ connectionId, authToken: jwtAuthToken });+ await testServer.inject({+ method: "DELETE",+ url: `/api/v1/projects/${projectId}`,+ headers: { authorization: `Bearer ${jwtAuthToken}` }+ });+ });++ 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([]);+ }+ );+ });++ describe("A rotation that cannot issue a credential changes nothing", () => {+ test("A provider that refuses the first credential leaves no rotation and no secrets", async () => {+ fakeIamUserSecret.failIssueWith("IAM denied CreateAccessKey");++ const { error } = await newRotation("issue-refused", { expectStatusCode: 400 });++ expect(error!.message).toContain("IAM denied CreateAccessKey");+ expect(fakeIamUserSecret.keys()).toEqual({});+ expect(await secretsAt("/services")).toEqual({});+ expect(await listSecretRotations({ projectId, authToken: jwtAuthToken })).toEqual([]);+ });++ test("A provider that refuses a later credential leaves the working one published", async () => {+ const { secretRotation } = await newRotation("issue-refused-later");+ const rotationId = secretRotation!.id;++ fakeIamUserSecret.failIssueWith("IAM throttled CreateAccessKey");++ // 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 });+ 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));++ const failed = await getSecretRotation({ rotationId, authToken: jwtAuthToken });+ expect(failed.rotationStatus).toBe(SecretRotationStatus.Failed);+ expect(failed.lastRotationMessage).toContain("IAM throttled CreateAccessKey");+ expect(failed.activeIndex).toBe(0);+ });++ test("A provider that fails after the new credential is published reports failure on a rotation that happened", async () => {+ const { secretRotation } = await newRotation("fails-after-publish");+ const rotationId = secretRotation!.id;++ fakeIamUserSecret.failAfterPersistWith("IAM denied DeleteAccessKey");++ const { error } = await rotateSecretRotation({ rotationId, authToken: jwtAuthToken, 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(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 () => {+ await newRotation("taken-name");++ const sameName = 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", {+ 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);++ // 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"+ });+ });+ });++ describe("The rotation owns its mapped secrets until it is deleted", () => {+ test("A mapped secret cannot be given a value by hand", async () => {+ await newRotation("owns-secrets");++ const { error } = await updateSecretV2({+ workspaceId: projectId,+ environmentSlug: ENV,+ secretPath: "/services",+ key: MAPPING.accessKeyId,+ value: "hand-written-value",+ authToken: jwtAuthToken,+ expectStatusCode: 400+ });++ expect(error!.message).toContain("Cannot update rotated secret");+ expect(await secretsAt("/services")).toEqual(mappedSecretsFor(1));+ });++ test("Deleting a rotation without revoking or deleting 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+ });++ // 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));++ // Nothing owns the secrets now, so the write the previous test was refused succeeds.+ await updateSecretV2({+ workspaceId: projectId,+ environmentSlug: ENV,+ secretPath: "/services",+ key: MAPPING.accessKeyId,+ value: "hand-written-value",+ authToken: jwtAuthToken+ });++ expect((await secretsAt("/services"))[MAPPING.accessKeyId]).toBe("hand-written-value");+ });+ });++ describe("A credential check reports what the provider says about the active credential", () => {+ test("A credential revoked at the provider fails the check", async () => {+ const { secretRotation } = await newRotation("check-credentials");+ const rotationId = secretRotation!.id;++ await checkRotationCredentials({ rotationId, authToken: jwtAuthToken });++ fakeIamUserSecret.revokeOutOfBand(credential(1).accessKeyId);++ const error = await checkRotationCredentials({ rotationId, authToken: jwtAuthToken, 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));+ });+ });+});diff --git a/backend/e2e-test/setup/reset-fakes.ts b/backend/e2e-test/setup/reset-fakes.tsindex a4825d0293..8f20e20bba 100644--- a/backend/e2e-test/setup/reset-fakes.ts+++ b/backend/e2e-test/setup/reset-fakes.ts@@ -1,4 +1,5 @@import { fakeAwsConnection } from "e2e-test/fakes/aws-connection-fns";+import { fakeIamUserSecret } from "e2e-test/fakes/aws-iam-user-secret-rotation-fns";import { fakeParameterStore } from "e2e-test/fakes/aws-parameter-store-sync-fns";// The fakes are module singletons shared with the server booted in this same process, and the@@ -14,4 +15,5 @@ import { fakeParameterStore } from "e2e-test/fakes/aws-parameter-store-sync-fns"beforeAll(() => {fakeParameterStore.reset();fakeAwsConnection.reset();+ fakeIamUserSecret.reset();});diff --git a/backend/e2e-test/testUtils/secret-rotations.ts b/backend/e2e-test/testUtils/secret-rotations.tsnew file mode 100644index 0000000000..e556991381--- /dev/null+++ b/backend/e2e-test/testUtils/secret-rotations.ts@@ -0,0 +1,161 @@+import { SecretRotation } from "@app/ee/services/secret-rotation-v2/secret-rotation-v2-enums";++// Every spec drives the AWS IAM user secret rotation, which is faked for the whole e2e run. See+// e2e-test/fakes/aws-iam-user-secret-rotation-fns.ts and the alias block in+// vitest.e2e.config.mts. A second faked provider should take the type as an argument rather than+// copy this file.+const ROTATION = SecretRotation.AwsIamUserSecret;++export type TSecretRotationRecord = {+ id: string;+ name: string;+ activeIndex: number;+ rotationStatus: string;+ lastRotationMessage: string | null;+ isAutoRotationEnabled: boolean;+ nextRotationAt: string | null;+ lastRotatedAt: string;+};++type TGeneratedCredentials = { accessKeyId: string; secretAccessKey: string }[];++export const createSecretRotation = async (dto: {+ name: string;+ projectId: string;+ connectionId: string;+ environmentSlug: string;+ secretPath: string;+ // The two keys the rotation writes its credentials to. Everything a spec asserts about what+ // reaches the secret path is addressed by these.+ secretsMapping: { accessKeyId: string; secretAccessKey: string };+ userName?: string;+ isAutoRotationEnabled?: boolean;+ rotationInterval?: number;+ authToken: string;+ expectStatusCode?: number;+}) => {+ const res = await testServer.inject({+ method: "POST",+ url: `/api/v2/secret-rotations/${ROTATION}`,+ headers: { authorization: `Bearer ${dto.authToken}` },+ body: {+ name: dto.name,+ projectId: dto.projectId,+ connectionId: dto.connectionId,+ environment: dto.environmentSlug,+ secretPath: dto.secretPath,+ parameters: { userName: dto.userName ?? "infisical-e2e" },+ secretsMapping: dto.secretsMapping,+ // Off unless a spec asks for it: under NODE_ENV=test the rotation cron treats every+ // auto-enabled rotation as due and rotates it inline every minute, so one left enabled+ // would rotate underneath whichever spec is running when the minute turns.+ isAutoRotationEnabled: dto.isAutoRotationEnabled ?? false,+ rotationInterval: dto.rotationInterval ?? 30+ }+ });++ expect(res.statusCode).toBe(dto.expectStatusCode ?? 200);++ // A spec asserting a rejection wants the body, not an id.+ if ((dto.expectStatusCode ?? 200) !== 200) return { error: res.json() as { message: string } };++ return { secretRotation: res.json().secretRotation as TSecretRotationRecord };+};++// Rotates synchronously: the route awaits rotateGeneratedCredentials and answers with the+// updated rotation, so nothing here has to poll. The cron reaches the same service function.+export const rotateSecretRotation = async (dto: {+ rotationId: string;+ authToken: string;+ expectStatusCode?: number;+}) => {+ const res = await testServer.inject({+ method: "POST",+ url: `/api/v2/secret-rotations/${ROTATION}/${dto.rotationId}/rotate-secrets`,+ headers: { authorization: `Bearer ${dto.authToken}` }+ });++ expect(res.statusCode).toBe(dto.expectStatusCode ?? 200);++ if ((dto.expectStatusCode ?? 200) !== 200) return { error: res.json() as { message: string } };++ return { secretRotation: res.json().secretRotation as TSecretRotationRecord };+};++export const getSecretRotation = async (dto: { rotationId: string; authToken: string }) => {+ const res = await testServer.inject({+ method: "GET",+ url: `/api/v2/secret-rotations/${ROTATION}/${dto.rotationId}`,+ headers: { authorization: `Bearer ${dto.authToken}` }+ });++ expect(res.statusCode).toBe(200);+ return res.json().secretRotation as TSecretRotationRecord;+};++export const getGeneratedCredentials = async (dto: { rotationId: string; authToken: string }) => {+ const res = await testServer.inject({+ method: "GET",+ url: `/api/v2/secret-rotations/${ROTATION}/${dto.rotationId}/generated-credentials`,+ headers: { authorization: `Bearer ${dto.authToken}` }+ });++ expect(res.statusCode).toBe(200);++ // The route also answers with the rotation id and type, which every caller already knows.+ const { generatedCredentials, activeIndex } = res.json() as {+ generatedCredentials: TGeneratedCredentials;+ activeIndex: number;+ };++ return { generatedCredentials, activeIndex };+};++// Answers 204 with no body when the active credentials still work, and 400 with the provider's+// message when they do not.+export const checkRotationCredentials = async (dto: {+ rotationId: string;+ authToken: string;+ expectStatusCode?: number;+}) => {+ const res = await testServer.inject({+ method: "POST",+ url: `/api/v2/secret-rotations/${ROTATION}/${dto.rotationId}/check-credentials`,+ headers: { authorization: `Bearer ${dto.authToken}` }+ });++ expect(res.statusCode).toBe(dto.expectStatusCode ?? 204);++ return res.statusCode === 204 ? undefined : (res.json() as { message: string });+};++export const deleteSecretRotation = async (dto: {+ rotationId: string;+ deleteSecrets: boolean;+ revokeGeneratedCredentials: boolean;+ authToken: string;+}) => {+ const res = await testServer.inject({+ method: "DELETE",+ url: `/api/v2/secret-rotations/${ROTATION}/${dto.rotationId}`,+ headers: { authorization: `Bearer ${dto.authToken}` },+ query: {+ deleteSecrets: String(dto.deleteSecrets),+ revokeGeneratedCredentials: String(dto.revokeGeneratedCredentials)+ }+ });++ expect(res.statusCode).toBe(200);+};++export const listSecretRotations = async (dto: { projectId: string; authToken: string }) => {+ const res = await testServer.inject({+ method: "GET",+ url: `/api/v2/secret-rotations/${ROTATION}`,+ headers: { authorization: `Bearer ${dto.authToken}` },+ query: { projectId: dto.projectId }+ });++ expect(res.statusCode).toBe(200);+ return res.json().secretRotations as TSecretRotationRecord[];+};diff --git a/backend/e2e-test/testUtils/secrets.ts b/backend/e2e-test/testUtils/secrets.tsindex 68e813442c..874b0da65a 100644--- a/backend/e2e-test/testUtils/secrets.ts+++ b/backend/e2e-test/testUtils/secrets.ts@@ -40,6 +40,39 @@ export const createSecretV2 = async (dto: {return createdSecretPayload.secret as TRawSecret;};+export const updateSecretV2 = async (dto: {+ workspaceId: string;+ environmentSlug: string;+ secretPath: string;+ key: string;+ value?: string;+ newKey?: string;+ authToken: string;+ expectStatusCode?: number;+}) => {+ const updateSecRes = await testServer.inject({+ method: "PATCH",+ url: `/api/v3/secrets/raw/${dto.key}`,+ headers: {+ authorization: `Bearer ${dto.authToken}`+ },+ body: {+ workspaceId: dto.workspaceId,+ environment: dto.environmentSlug,+ secretPath: dto.secretPath,+ secretValue: dto.value,+ newSecretName: dto.newKey+ }+ });++ expect(updateSecRes.statusCode).toBe(dto.expectStatusCode ?? 200);++ // A spec asserting a rejection wants the body, not the secret.+ if ((dto.expectStatusCode ?? 200) !== 200) return { error: JSON.parse(updateSecRes.payload) as { message: string } };++ return { secret: JSON.parse(updateSecRes.payload).secret as TRawSecret };+};+export const deleteSecretV2 = async (dto: {workspaceId: string;environmentSlug: string;diff --git a/backend/vitest.e2e.config.mts b/backend/vitest.e2e.config.mtsindex 02d3c0fedf..3ff5a10ca5 100644--- a/backend/vitest.e2e.config.mts+++ b/backend/vitest.e2e.config.mts@@ -49,16 +49,18 @@ export default defineConfig({},fileParallelism: false,- // AWS Parameter Store and the AWS app connection are replaced by fakes for the whole e2e- // run, so the secret sync specs can assert what Infisical hands a destination without- // reaching AWS. Nothing under src/ knows the fakes exist — see e2e-test/fakes/.+ // AWS Parameter Store, the AWS IAM user secret rotation provider and the AWS app connection+ // are replaced by fakes for the whole e2e run, so the secret sync and secret rotation specs+ // can assert what Infisical hands a destination or a rotation provider without reaching AWS.+ // Nothing under src/ knows the fakes exist (see e2e-test/fakes/).//// Entries match the *import specifier*, which is what keeps this surgical rather than- // sweeping: "./aws-parameter-store-sync-fns" is imported only by its own barrel, and- // "./aws-connection-fns" only by aws/index.ts. The full-path entry covers the twelve- // modules that import the connection functions directly, of which secret-sync-maps.ts- // matters here: it calls getAwsAccountId on every sync creation, which would otherwise be- // a real STS request that fails slowly and silently.+ // sweeping: "./aws-parameter-store-sync-fns" is imported only by its own barrel,+ // "./aws-iam-user-secret/aws-iam-user-secret-rotation-fns" only by+ // secret-rotation-v2-service.ts, and "./aws-connection-fns" only by aws/index.ts. The+ // full-path entry covers the twelve modules that import the connection functions directly,+ // of which secret-sync-maps.ts matters here: it calls getAwsAccountId on every sync+ // creation, which would otherwise be a real STS request that fails slowly and silently.//// An ordered array rather than an object so the exact @app/… entry is matched before the// generic "@app" prefix alias in resolve.alias below.@@ -71,6 +73,10 @@ export default defineConfig({find: "./aws-parameter-store-sync-fns",replacement: path.resolve(__dirname, "./e2e-test/fakes/aws-parameter-store-sync-fns")},+ {+ find: "./aws-iam-user-secret/aws-iam-user-secret-rotation-fns",+ replacement: path.resolve(__dirname, "./e2e-test/fakes/aws-iam-user-secret-rotation-fns")+ },{find: /^@app\/services\/app-connection\/aws\/aws-connection-fns$/,replacement: path.resolve(__dirname, "./e2e-test/fakes/aws-connection-fns")