Skip to content

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

feat(secret-rotation): add Stripe API key rotation factory

Calvin1969e2a8d7d0
diff --git a/backend/src/ee/services/secret-rotation-v2/stripe-api-key/stripe-api-key-rotation-fns.test.ts b/backend/src/ee/services/secret-rotation-v2/stripe-api-key/stripe-api-key-rotation-fns.test.ts
new file mode 100644
index 0000000000..05a86145e7
--- /dev/null
+++ b/backend/src/ee/services/secret-rotation-v2/stripe-api-key/stripe-api-key-rotation-fns.test.ts
@@ -0,0 +1,168 @@
+/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-argument */
+import { AxiosError } from "axios";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const { getMock, postMock } = vi.hoisted(() => ({ getMock: vi.fn(), postMock: vi.fn() }));
+
+vi.mock("@app/lib/config/env", () => ({
+ getConfig: () => ({ INF_APP_CONNECTION_STRIPE_SECRET_KEY: "sk_test_platform" })
+}));
+vi.mock("@app/lib/config/request", () => ({
+ request: {
+ get: (...args: unknown[]) => (getMock as any)(...args),
+ post: (...args: unknown[]) => (postMock as any)(...args)
+ }
+}));
+vi.mock("@app/lib/logger", () => ({
+ logger: { error: vi.fn(), info: vi.fn(), warn: vi.fn(), debug: vi.fn() }
+}));
+
+// eslint-disable-next-line import/first
+import { stripeApiKeyRotationFactory } from "./stripe-api-key-rotation-fns";
+
+const httpError = (status: number, message = "boom") =>
+ new AxiosError("Request failed", "ERR_BAD_REQUEST", undefined, undefined, {
+ status,
+ statusText: "",
+ headers: {},
+ config: {} as any,
+ data: { error: { message } }
+ });
+
+const makeFactory = () =>
+ stripeApiKeyRotationFactory(
+ {
+ connection: { id: "connection-id", credentials: { accountId: "acct_123" } },
+ parameters: { permissions: ["customer_read"], connectPermissions: [] },
+ secretsMapping: { apiKey: "STRIPE_API_KEY" }
+ } as any,
+ {} as any,
+ {} as any,
+ {} as any,
+ {} as any,
+ {} as any
+ );
+
+const isCreate = (url: string) => url.endsWith("/v2/iam/api_keys");
+const isExpire = (url: string) => url.endsWith("/expire");
+const expireCalls = (keyId?: string) =>
+ postMock.mock.calls.filter(([url]) => isExpire(url) && (keyId === undefined || url.includes(`/${keyId}/expire`)));
+
+/** Test mode returns the secret in plaintext, which is the shape the sandbox produces. */
+const mockStripe = ({
+ createIds = ["mk_new"],
+ expire = async () => ({ data: {} })
+}: { createIds?: string[]; expire?: (keyId: string) => Promise<unknown> } = {}) => {
+ const ids = [...createIds];
+ postMock.mockImplementation(async (url: string) => {
+ if (isCreate(url)) {
+ const id = ids.shift() ?? "mk_extra";
+ return { data: { id, secret_key: { token: `rk_test_${id}` } } };
+ }
+ if (isExpire(url)) return expire(url.split("/").slice(-2)[0]);
+ throw new Error(`unexpected request to ${url}`);
+ });
+};
+
+describe("stripeApiKeyRotationFactory", () => {
+ beforeEach(() => {
+ getMock.mockReset();
+ postMock.mockReset();
+ });
+
+ it("mints a key and hands the plaintext secret to the callback", async () => {
+ mockStripe();
+ const callback = vi.fn(async (credentials: unknown) => credentials);
+
+ const result = await makeFactory().issueCredentials(callback as any);
+
+ expect(result).toEqual({ keyId: "mk_new", apiKey: "rk_test_mk_new" });
+ const [, body] = postMock.mock.calls.find(([url]) => isCreate(url))!;
+ expect(body.type).toBe("secret_key");
+ expect(body.permissions).toEqual(["customer_read"]);
+ expect(body.public_key.pem_key.data).toContain("BEGIN PUBLIC KEY");
+ });
+
+ it("expires the new key when the create commit fails", async () => {
+ mockStripe();
+ const callback = vi.fn(async () => {
+ throw new Error("conflicting secret");
+ });
+
+ await expect(makeFactory().issueCredentials(callback as any)).rejects.toThrow("conflicting secret");
+ expect(expireCalls("mk_new")).toHaveLength(1);
+ });
+
+ it("retires the previous key before committing the new one", async () => {
+ mockStripe({ createIds: ["mk_new"] });
+ const callback = vi.fn(async (credentials: unknown) => credentials);
+
+ await makeFactory().rotateCredentials({ keyId: "mk_old", apiKey: "rk_old" } as any, callback as any, {} as any);
+
+ const order = postMock.mock.calls.map(([url]) => (isCreate(url) ? "create" : url.split("/").slice(-2)[0]));
+ expect(order).toEqual(["create", "mk_old"]);
+ expect(callback).toHaveBeenCalledWith({ keyId: "mk_new", apiKey: "rk_test_mk_new" });
+ });
+
+ it("cleans up the new key and fails when the retirement fails", async () => {
+ mockStripe({
+ expire: async (keyId) => {
+ if (keyId === "mk_old") throw httpError(500, "Stripe is down");
+ return { data: {} };
+ }
+ });
+ const callback = vi.fn(async (credentials: unknown) => credentials);
+
+ await expect(
+ makeFactory().rotateCredentials({ keyId: "mk_old" } as any, callback as any, {} as any)
+ ).rejects.toThrow("Stripe is down");
+
+ expect(expireCalls("mk_new")).toHaveLength(1);
+ expect(callback).not.toHaveBeenCalled();
+ });
+
+ it("names the stranded key when the cleanup also fails", async () => {
+ mockStripe({
+ expire: async () => {
+ throw httpError(500, "Stripe is down");
+ }
+ });
+ const callback = vi.fn(async (credentials: unknown) => credentials);
+
+ await expect(
+ makeFactory().rotateCredentials({ keyId: "mk_old" } as any, callback as any, {} as any)
+ ).rejects.toThrow(/mk_new/);
+ });
+
+ it("treats a 404 on expire as already gone", async () => {
+ mockStripe({
+ expire: async (keyId) => {
+ if (keyId === "mk_old") throw httpError(404, "No such key");
+ return { data: {} };
+ }
+ });
+ const callback = vi.fn(async (credentials: unknown) => credentials);
+
+ await expect(
+ makeFactory().rotateCredentials({ keyId: "mk_old" } as any, callback as any, {} as any)
+ ).resolves.toBeDefined();
+ });
+
+ it("maps only the API key into the secrets payload", () => {
+ expect(makeFactory().getSecretsPayload({ keyId: "mk_new", apiKey: "rk_test" } as any)).toEqual([
+ { key: "STRIPE_API_KEY", value: "rk_test" }
+ ]);
+ });
+
+ it("treats 403 as a live key and 401 as a dead one", async () => {
+ getMock.mockRejectedValueOnce(httpError(403, "Insufficient permissions"));
+ await expect(
+ makeFactory().checkActiveCredentials!({ keyId: "mk", apiKey: "rk_test" } as any)
+ ).resolves.toBeUndefined();
+
+ getMock.mockRejectedValueOnce(httpError(401, "Invalid API Key"));
+ await expect(makeFactory().checkActiveCredentials!({ keyId: "mk", apiKey: "rk_test" } as any)).rejects.toThrow(
+ "Invalid API Key"
+ );
+ });
+});
diff --git a/backend/src/ee/services/secret-rotation-v2/stripe-api-key/stripe-api-key-rotation-fns.ts b/backend/src/ee/services/secret-rotation-v2/stripe-api-key/stripe-api-key-rotation-fns.ts
new file mode 100644
index 0000000000..5e292b889d
--- /dev/null
+++ b/backend/src/ee/services/secret-rotation-v2/stripe-api-key/stripe-api-key-rotation-fns.ts
@@ -0,0 +1,195 @@
+import {
+ TRotationFactory,
+ TRotationFactoryCheckActiveCredentials,
+ TRotationFactoryGetSecretsPayload,
+ TRotationFactoryIssueCredentials,
+ TRotationFactoryRevokeCredentials,
+ TRotationFactoryRotateCredentials
+} from "@app/ee/services/secret-rotation-v2/secret-rotation-v2-types";
+import { request } from "@app/lib/config/request";
+import { BadRequestError } from "@app/lib/errors";
+import {
+ getStripeErrorMessage,
+ getStripeErrorStatus,
+ getStripeMerchantRequestConfig,
+ getStripePlatformRequestConfig,
+ STRIPE_API_KEYS_URL,
+ throwStripeApiKeyManagementError,
+ withIdempotencyKey
+} from "@app/services/app-connection/stripe/stripe-connection-public-client";
+import { IntegrationUrls } from "@app/services/integration-auth/integration-list";
+
+import { generateStripeEncryptionKeyPair, readStripeSecret } from "./stripe-api-key-jwe";
+import {
+ TStripeApiKeyCreateResponse,
+ TStripeApiKeyRotationGeneratedCredentials,
+ TStripeApiKeyRotationWithConnection
+} from "./stripe-api-key-rotation-types";
+
+const STRIPE_KEY_NAME_MAX_LENGTH = 100;
+
+const getErrorMessage = (error: unknown): string => (error instanceof Error ? error.message : "Unknown error");
+
+export const stripeApiKeyRotationFactory: TRotationFactory<
+ TStripeApiKeyRotationWithConnection,
+ TStripeApiKeyRotationGeneratedCredentials
+> = (secretRotation) => {
+ const {
+ connection,
+ parameters: { permissions, connectPermissions },
+ secretsMapping
+ } = secretRotation;
+
+ const { accountId } = connection.credentials;
+
+ // The factory is built without an id at create time, so the name comes from the mapped secret.
+ // It is what makes a key stranded by a timed-out create identifiable in the Stripe dashboard.
+ const $keyName = () => `infisical-${secretsMapping.apiKey}-${Date.now()}`.slice(0, STRIPE_KEY_NAME_MAX_LENGTH);
+
+ const $createApiKey = async () => {
+ const { publicKey, privateKey } = await generateStripeEncryptionKeyPair();
+
+ let data: TStripeApiKeyCreateResponse;
+
+ try {
+ ({ data } = await request.post<TStripeApiKeyCreateResponse>(
+ STRIPE_API_KEYS_URL,
+ {
+ type: "secret_key",
+ name: $keyName(),
+ permissions,
+ ...(connectPermissions?.length ? { connect_permissions: connectPermissions } : {}),
+ public_key: { pem_key: { data: publicKey, algorithm: "RSA" } }
+ },
+ withIdempotencyKey(getStripePlatformRequestConfig(accountId))
+ ));
+ } catch (error) {
+ return throwStripeApiKeyManagementError(accountId, error);
+ }
+
+ if (!data?.id) {
+ throw new BadRequestError({ message: "Stripe did not return an ID for the created API key." });
+ }
+
+ return { keyId: data.id, apiKey: readStripeSecret(data.secret_key, privateKey) };
+ };
+
+ /**
+ * Expire is the whole retirement. Stripe decides when it takes effect, so nothing here claims the
+ * key is dead. Narrowing the key's permissions first would stop it sooner, and was measured
+ * working, but is deliberately not in v1. See the design doc.
+ */
+ const $retireKey = async (keyId: string) => {
+ try {
+ await request.post(
+ `${STRIPE_API_KEYS_URL}/${keyId}/expire`,
+ {},
+ withIdempotencyKey(getStripePlatformRequestConfig(accountId))
+ );
+ } catch (error) {
+ if (getStripeErrorStatus(error) === 404) return;
+
+ throwStripeApiKeyManagementError(accountId, error);
+ }
+ };
+
+ /** A key exists in Stripe before the row does, so a failed commit has to take the key with it. */
+ const $commitOrCleanUp = async <T>(
+ credentials: { keyId: string; apiKey: string },
+ callback: (credentials: { keyId: string; apiKey: string }) => Promise<T>
+ ): Promise<T> => {
+ try {
+ return await callback(credentials);
+ } catch (commitError) {
+ try {
+ await $retireKey(credentials.keyId);
+ } catch (cleanupError) {
+ throw new BadRequestError({
+ message: `${getErrorMessage(commitError)} The newly created Stripe API key ${credentials.keyId} could not be expired and may need to be removed manually: ${getErrorMessage(cleanupError)}`
+ });
+ }
+
+ throw commitError;
+ }
+ };
+
+ const issueCredentials: TRotationFactoryIssueCredentials<TStripeApiKeyRotationGeneratedCredentials> = async (
+ callback
+ ) => {
+ const credentials = await $createApiKey();
+
+ return $commitOrCleanUp(credentials, callback);
+ };
+
+ const revokeCredentials: TRotationFactoryRevokeCredentials<TStripeApiKeyRotationGeneratedCredentials> = async (
+ credentials,
+ callback
+ ) => {
+ if (!credentials?.length) return callback();
+
+ for (const { keyId } of credentials) {
+ // eslint-disable-next-line no-await-in-loop
+ await $retireKey(keyId);
+ }
+
+ return callback();
+ };
+
+ const rotateCredentials: TRotationFactoryRotateCredentials<TStripeApiKeyRotationGeneratedCredentials> = async (
+ credentialsToRevoke,
+ callback
+ ) => {
+ const newCredentials = await $createApiKey();
+
+ // Retire before committing, so a failure leaves Postgres and Stripe agreeing with each other and
+ // the key we just minted gets cleaned up rather than orphaned across BullMQ's retries.
+ if (credentialsToRevoke?.keyId) {
+ try {
+ await $retireKey(credentialsToRevoke.keyId);
+ } catch (retireError) {
+ try {
+ await $retireKey(newCredentials.keyId);
+ } catch (cleanupError) {
+ throw new BadRequestError({
+ message: `${getErrorMessage(retireError)} The newly created Stripe API key ${newCredentials.keyId} could not be expired and may need to be removed manually: ${getErrorMessage(cleanupError)}`
+ });
+ }
+
+ throw retireError;
+ }
+ }
+
+ return $commitOrCleanUp(newCredentials, callback);
+ };
+
+ const getSecretsPayload: TRotationFactoryGetSecretsPayload<TStripeApiKeyRotationGeneratedCredentials> = ({
+ apiKey
+ }) => [{ key: secretsMapping.apiKey, value: apiKey }];
+
+ const checkActiveCredentials: TRotationFactoryCheckActiveCredentials<
+ TStripeApiKeyRotationGeneratedCredentials
+ > = async ({ apiKey }) => {
+ try {
+ await request.get(
+ `${IntegrationUrls.STRIPE_API_URL}/v1/customers?limit=1`,
+ getStripeMerchantRequestConfig(apiKey)
+ );
+ } catch (error) {
+ // 403 means the key authenticated and simply lacks customer_read, which is a healthy narrow
+ // key. Only 401 means the key is gone.
+ if (getStripeErrorStatus(error) === 403) return;
+
+ throw new BadRequestError({
+ message: `Stripe API key verification failed: ${getStripeErrorMessage(error)}`
+ });
+ }
+ };
+
+ return {
+ issueCredentials,
+ revokeCredentials,
+ rotateCredentials,
+ getSecretsPayload,
+ checkActiveCredentials
+ };
+};