Skip to content

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

fix(secret-rotation): retire the published Stripe key last on revoke

Calvina05acdfac825
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
index d9bb429f0a..ad35de8635 100644
--- 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
@@ -1,17 +1,18 @@
-/* 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() }));
+import { TSecretRotationV2Raw } from "@app/ee/services/secret-rotation-v2/secret-rotation-v2-types";
+
+const { getMock, postMock } = vi.hoisted(() => ({
+ getMock: vi.fn<(url: string, config?: unknown) => Promise<unknown>>(),
+ postMock: vi.fn<(url: string, body?: unknown, config?: unknown) => Promise<unknown>>()
+}));
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)
- }
+ request: { get: getMock, post: postMock }
}));
vi.mock("@app/lib/logger", () => ({
logger: { error: vi.fn(), info: vi.fn(), warn: vi.fn(), debug: vi.fn() }
@@ -19,286 +20,278 @@ vi.mock("@app/lib/logger", () => ({
// eslint-disable-next-line import/first
import { stripeApiKeyRotationFactory } from "./stripe-api-key-rotation-fns";
+// eslint-disable-next-line import/first
+import {
+ TStripeApiKeyRotationGeneratedCredentials,
+ TStripeApiKeyRotationWithConnection
+} from "./stripe-api-key-rotation-types";
-const httpError = (status: number, message = "boom") =>
- new AxiosError("Request failed", "ERR_BAD_REQUEST", undefined, undefined, {
- status,
- statusText: "",
- headers: {},
- config: {} as any,
- data: { error: { message } }
- });
+type TCredential = TStripeApiKeyRotationGeneratedCredentials[number];
+
+type TCreateKeyRequest = {
+ type: string;
+ permissions: string[];
+ public_key: { pem_key: { data: string } };
+};
-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 OLD_KEY: TCredential = { keyId: "mk_old", apiKey: "rk_old" };
+const NEW_KEY: TCredential = { keyId: "mk_new", apiKey: "rk_test_mk_new" };
+
+/** The rotation service hands the factory a transaction body; this stands in for its return. */
+const COMMITTED = "committed" as unknown as TSecretRotationV2Raw;
+
+// The Stripe factory reaches Stripe over HTTP and touches none of the other four dependencies.
+const UNUSED_DEPENDENCIES = [{}, {}, {}, {}] as unknown as [
+ Parameters<typeof stripeApiKeyRotationFactory>[1],
+ Parameters<typeof stripeApiKeyRotationFactory>[2],
+ Parameters<typeof stripeApiKeyRotationFactory>[3],
+ Parameters<typeof stripeApiKeyRotationFactory>[4]
+];
+
+// The factory reads these four fields of the rotation row and nothing else, so the rest of the row
+// is left off rather than filled with placeholders that would read as though they mattered.
+const rotation = (activeIndex: number) =>
+ ({
+ connection: { id: "connection-id", credentials: { accountId: "acct_123" } },
+ parameters: { permissions: ["customer_read"], connectPermissions: [] },
+ secretsMapping: { apiKey: "STRIPE_API_KEY" },
+ activeIndex
+ }) as unknown as TStripeApiKeyRotationWithConnection;
+
+const makeFactory = ({ activeIndex = 0 }: { activeIndex?: number } = {}) =>
+ stripeApiKeyRotationFactory(rotation(activeIndex), ...UNUSED_DEPENDENCIES);
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`)));
+const expiredKeyId = (url: string) => url.split("/").slice(-2)[0];
+
+/** Every Stripe round trip and every commit, in the order they happened. */
+let calls: string[] = [];
+let createBody: TCreateKeyRequest | undefined;
-/** Test mode returns the secret in plaintext, which is the shape the sandbox produces. */
+/**
+ * Test mode returns the secret in plaintext, which is the shape the sandbox produces, so `omitSecret`
+ * is how a response the read path rejects is produced.
+ */
const mockStripe = ({
createIds = ["mk_new"],
- expire = async () => ({ data: {} })
-}: { createIds?: string[]; expire?: (keyId: string) => Promise<unknown> } = {}) => {
+ expire,
+ omitSecret = false
+}: {
+ createIds?: string[];
+ /** Throw to fail the expire of the named key; return to expire it. */
+ expire?: (keyId: string) => Promise<void>;
+ omitSecret?: boolean;
+} = {}) => {
const ids = [...createIds];
- postMock.mockImplementation(async (url: string) => {
+
+ postMock.mockImplementation(async (url, body) => {
if (isCreate(url)) {
const id = ids.shift() ?? "mk_extra";
- return { data: { id, secret_key: { token: `rk_test_${id}` } } };
+ calls.push("create");
+ createBody = body as TCreateKeyRequest;
+ return { data: { id, secret_key: omitSecret ? {} : { token: `rk_test_${id}` } } };
+ }
+
+ if (isExpire(url)) {
+ const keyId = expiredKeyId(url);
+ calls.push(`expire:${keyId}`);
+ await expire?.(keyId);
+ return { data: {} };
}
- if (isExpire(url)) return expire(url.split("/").slice(-2)[0]);
- throw new Error(`unexpected request to ${url}`);
+
+ throw new Error(`unexpected POST ${url}`);
});
};
-describe("stripeApiKeyRotationFactory", () => {
- beforeEach(() => {
- getMock.mockReset();
- postMock.mockReset();
+/** The existence check the factory falls back to when an expire fails with something other than 404. */
+const mockKeyLookup = (lookup: (keyId: string) => Promise<void>) => {
+ getMock.mockImplementation(async (url) => {
+ const keyId = url.split("/").pop()!;
+ calls.push(`lookup:${keyId}`);
+ await lookup(keyId);
+ return { data: { id: keyId } };
});
+};
- it("mints a key and hands the plaintext secret to the callback", async () => {
- mockStripe();
- const callback = vi.fn(async (credentials: unknown) => credentials);
+const httpError = (status: number, message: string) =>
+ new AxiosError("Request failed", "ERR_BAD_REQUEST", undefined, undefined, {
+ status,
+ statusText: "",
+ headers: {},
+ config: {} as never,
+ data: { error: { message } }
+ });
- const result = await makeFactory().issueCredentials(callback as any);
+const failsWith = (status: number, message: string, keyId: string) => async (expiredKey: string) => {
+ if (expiredKey === keyId) throw httpError(status, message);
+};
- 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");
- });
+const commit = vi.fn(async (credentials: TCredential) => {
+ calls.push("commit");
+ return credentials as unknown as TSecretRotationV2Raw;
+});
- it("expires the new key when the create commit fails", async () => {
- mockStripe();
- const callback = vi.fn(async () => {
- throw new Error("conflicting secret");
- });
+const commitWithoutCredentials = vi.fn(async () => {
+ calls.push("commit");
+ return COMMITTED;
+});
- await expect(makeFactory().issueCredentials(callback as any)).rejects.toThrow("conflicting secret");
- expect(expireCalls("mk_new")).toHaveLength(1);
+describe("stripeApiKeyRotationFactory", () => {
+ beforeEach(() => {
+ calls = [];
+ createBody = undefined;
+ getMock.mockReset();
+ postMock.mockReset();
+ commit.mockClear();
+ commitWithoutCredentials.mockClear();
});
- it("expires the new key when reading the returned secret fails", async () => {
- postMock.mockImplementation(async (url: string) => {
- if (isCreate(url)) return { data: { id: "mk_new", secret_key: {} } };
- if (isExpire(url)) return { data: {} };
- throw new Error(`unexpected request to ${url}`);
- });
- const callback = vi.fn(async (credentials: unknown) => credentials);
-
- await expect(makeFactory().issueCredentials(callback as any)).rejects.toThrow(
- "Stripe returned an API key without a secret"
- );
+ describe("issueCredentials", () => {
+ it("mints a key and hands the plaintext secret to the callback", async () => {
+ mockStripe();
- expect(expireCalls("mk_new")).toHaveLength(1);
- expect(callback).not.toHaveBeenCalled();
- });
+ const result = await makeFactory().issueCredentials(commit);
- it("retires the previous key before committing the new one", async () => {
- const order: string[] = [];
- postMock.mockImplementation(async (url: string) => {
- if (isCreate(url)) {
- order.push("create");
- return { data: { id: "mk_new", secret_key: { token: "rk_test_mk_new" } } };
- }
- if (isExpire(url)) {
- order.push(url.split("/").slice(-2)[0]);
- return { data: {} };
- }
- throw new Error(`unexpected request to ${url}`);
- });
- const callback = vi.fn(async (credentials: unknown) => {
- order.push("commit");
- return credentials;
+ expect(result).toEqual(NEW_KEY);
+ expect(createBody?.type).toBe("secret_key");
+ expect(createBody?.permissions).toEqual(["customer_read"]);
+ expect(createBody?.public_key.pem_key.data).toContain("BEGIN PUBLIC KEY");
});
- await makeFactory().rotateCredentials({ keyId: "mk_old", apiKey: "rk_old" } as any, callback as any, {} as any);
+ it("expires the new key when the commit fails", async () => {
+ mockStripe();
- expect(order).toEqual(["create", "mk_old", "commit"]);
- expect(callback).toHaveBeenCalledWith({ keyId: "mk_new", apiKey: "rk_test_mk_new" });
- });
+ await expect(
+ makeFactory().issueCredentials(async () => {
+ throw new Error("conflicting secret");
+ })
+ ).rejects.toThrow("conflicting secret");
- 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: {} };
- }
+ expect(calls).toEqual(["create", "expire:mk_new"]);
});
- 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");
+ it("expires the new key when reading the returned secret fails", async () => {
+ mockStripe({ omitSecret: true });
- expect(expireCalls("mk_new")).toHaveLength(1);
- expect(callback).not.toHaveBeenCalled();
- });
+ await expect(makeFactory().issueCredentials(commit)).rejects.toThrow(
+ "Stripe returned an API key without a secret"
+ );
- it("names the stranded key when the cleanup also fails", async () => {
- mockStripe({
- expire: async () => {
- throw httpError(500, "Stripe is down");
- }
+ expect(calls).toEqual(["create", "expire:mk_new"]);
+ expect(commit).not.toHaveBeenCalled();
});
- const callback = vi.fn(async (credentials: unknown) => credentials);
+ });
- let caughtMessage = "";
- try {
- await makeFactory().rotateCredentials({ keyId: "mk_old" } as any, callback as any, {} as any);
- } catch (error) {
- caughtMessage = (error as Error).message;
- }
+ describe("rotateCredentials", () => {
+ it("retires the previous key before committing the new one, and issues no GET", async () => {
+ mockStripe();
- expect(caughtMessage).toMatch(/mk_old/);
- expect(caughtMessage).toMatch(/mk_new/);
- });
+ await makeFactory().rotateCredentials(OLD_KEY, commit, OLD_KEY);
- 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: {} };
- }
+ expect(calls).toEqual(["create", "expire:mk_old", "commit"]);
+ expect(commit).toHaveBeenCalledWith(NEW_KEY);
+ expect(getMock).not.toHaveBeenCalled();
});
- 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("cleans up the new key and fails when retiring the previous one fails", async () => {
+ mockStripe({ expire: failsWith(500, "Stripe is down", "mk_old") });
+ mockKeyLookup(async () => {});
- it("completes a rotation when the old key is already gone from Stripe, via the existence check after a non-404 expire failure", async () => {
- // A double expire's response has never been observed, so a repeat expire is mocked to fail with
- // something other than 404 (a generic 400), and the existence check (a 404 on retrieve) is what
- // recognizes the key as already gone.
- getMock.mockImplementation(async (url: string) => {
- if (url.endsWith("/mk_old")) throw httpError(404, "No such key");
- throw new Error(`unexpected GET ${url}`);
- });
- mockStripe({
- expire: async (keyId) => {
- if (keyId === "mk_old") throw httpError(400, "Key is not active");
- return { data: {} };
- }
- });
- const callback = vi.fn(async (credentials: unknown) => credentials);
+ await expect(makeFactory().rotateCredentials(OLD_KEY, commit, OLD_KEY)).rejects.toThrow("Stripe is down");
- await expect(
- makeFactory().rotateCredentials({ keyId: "mk_old" } as any, callback as any, {} as any)
- ).resolves.toBeDefined();
+ expect(calls).toEqual(["create", "expire:mk_old", "lookup:mk_old", "expire:mk_new"]);
+ expect(commit).not.toHaveBeenCalled();
+ });
- expect(expireCalls("mk_old")).toHaveLength(1);
- expect(callback).toHaveBeenCalled();
- });
+ it("names both stranded keys when the cleanup also fails", async () => {
+ mockStripe({
+ expire: async () => {
+ throw httpError(500, "Stripe is down");
+ }
+ });
+ mockKeyLookup(async () => {});
- it("issues no GET at all on the happy path", async () => {
- mockStripe();
- const callback = vi.fn(async (credentials: unknown) => credentials);
+ await expect(makeFactory().rotateCredentials(OLD_KEY, commit, OLD_KEY)).rejects.toThrow(/mk_old.*mk_new/s);
+ });
- await makeFactory().rotateCredentials({ keyId: "mk_old", apiKey: "rk_old" } as any, callback as any, {} as any);
+ it("treats a 404 on expire as already gone", async () => {
+ mockStripe({ expire: failsWith(404, "No such key", "mk_old") });
- expect(getMock).not.toHaveBeenCalled();
- });
+ await expect(makeFactory().rotateCredentials(OLD_KEY, commit, OLD_KEY)).resolves.toEqual(NEW_KEY);
- it("surfaces the original expire error, not the existence check's error, when the check itself fails", async () => {
- getMock.mockImplementation(async (url: string) => {
- if (url.endsWith("/mk_old")) throw httpError(500, "Stripe existence check is down");
- throw new Error(`unexpected GET ${url}`);
+ expect(getMock).not.toHaveBeenCalled();
});
- mockStripe({
- expire: async (keyId) => {
- if (keyId === "mk_old") throw httpError(400, "Key is not active");
- 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("Key is not active");
- });
+ it("completes when the existence check finds the previous key already gone", async () => {
+ // A double expire's response has never been observed, so a repeat expire is mocked to fail with
+ // something other than 404 (a generic 400), and the existence check is what recognizes the key
+ // as already gone.
+ mockStripe({ expire: failsWith(400, "Key is not active", "mk_old") });
+ mockKeyLookup(async () => {
+ throw httpError(404, "No such key");
+ });
- it("revokeCredentials returns early without contacting Stripe when there are no credentials", async () => {
- const callback = vi.fn(async () => "done");
+ await expect(makeFactory().rotateCredentials(OLD_KEY, commit, OLD_KEY)).resolves.toEqual(NEW_KEY);
- const result = await makeFactory().revokeCredentials([] as any, callback as any);
+ expect(calls).toEqual(["create", "expire:mk_old", "lookup:mk_old", "commit"]);
+ });
- expect(result).toBe("done");
- expect(postMock).not.toHaveBeenCalled();
- });
+ it("surfaces the original expire error, not the existence check's error, when the check itself fails", async () => {
+ mockStripe({ expire: failsWith(400, "Key is not active", "mk_old") });
+ mockKeyLookup(async () => {
+ throw httpError(500, "Stripe existence check is down");
+ });
- it("revokeCredentials expires every key it is given", async () => {
- mockStripe();
- const callback = vi.fn(async () => "done");
-
- const result = await makeFactory().revokeCredentials(
- [
- { keyId: "mk_one", apiKey: "rk_one" },
- { keyId: "mk_two", apiKey: "rk_two" }
- ] as any,
- callback as any
- );
-
- expect(expireCalls("mk_one")).toHaveLength(1);
- expect(expireCalls("mk_two")).toHaveLength(1);
- expect(result).toBe("done");
+ await expect(makeFactory().rotateCredentials(OLD_KEY, commit, OLD_KEY)).rejects.toThrow("Key is not active");
+ });
});
- it("revokeCredentials stops at the first failure and never calls back", async () => {
- mockStripe({
- expire: async (keyId) => {
- if (keyId === "mk_two") throw httpError(500, "Stripe is down");
- return { data: {} };
- }
- });
- const callback = vi.fn(async () => "done");
+ describe("revokeCredentials", () => {
+ it.each([
+ { activeIndex: 0, expected: ["expire:mk_two", "expire:mk_one", "commit"] },
+ { activeIndex: 1, expected: ["expire:mk_one", "expire:mk_two", "commit"] }
+ ])("retires the published key last (activeIndex $activeIndex)", async ({ activeIndex, expected }) => {
+ mockStripe();
- await expect(
- makeFactory().revokeCredentials(
+ const result = await makeFactory({ activeIndex }).revokeCredentials(
[
{ keyId: "mk_one", apiKey: "rk_one" },
{ keyId: "mk_two", apiKey: "rk_two" }
- ] as any,
- callback as any
- )
- ).rejects.toThrow("Stripe is down");
-
- expect(expireCalls("mk_one")).toHaveLength(1);
- expect(expireCalls("mk_two")).toHaveLength(1);
- expect(callback).not.toHaveBeenCalled();
- });
+ ],
+ commitWithoutCredentials
+ );
- 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" }
- ]);
+ expect(calls).toEqual(expected);
+ expect(result).toBe(COMMITTED);
+ });
+
+ it("stops at the first failure and never calls back", async () => {
+ mockStripe({ expire: failsWith(500, "Stripe is down", "mk_two") });
+ mockKeyLookup(async () => {});
+
+ await expect(
+ makeFactory({ activeIndex: 1 }).revokeCredentials(
+ [
+ { keyId: "mk_one", apiKey: "rk_one" },
+ { keyId: "mk_two", apiKey: "rk_two" }
+ ],
+ commitWithoutCredentials
+ )
+ ).rejects.toThrow("Stripe is down");
+
+ expect(calls).toEqual(["expire:mk_one", "expire:mk_two", "lookup:mk_two"]);
+ expect(commitWithoutCredentials).not.toHaveBeenCalled();
+ });
});
- 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();
+ describe("checkActiveCredentials", () => {
+ it("treats 403 as a live key and 401 as a dead one", async () => {
+ getMock.mockRejectedValueOnce(httpError(403, "Insufficient permissions"));
+ await expect(makeFactory().checkActiveCredentials!(NEW_KEY)).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"
- );
+ getMock.mockRejectedValueOnce(httpError(401, "Invalid API Key"));
+ await expect(makeFactory().checkActiveCredentials!(NEW_KEY)).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
index 6fcf8c7c03..7ff73946f1 100644
--- 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
@@ -89,8 +89,8 @@ export const stripeApiKeyRotationFactory: TRotationFactory<
/**
* 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.
+ * key is dead the moment this returns. In practice the key stops working within several minutes,
+ * which is well inside the weeks-to-months cadence rotations run on.
*/
const $retireKey = async (keyId: string) => {
const result = await $tryRetireKey(keyId);
@@ -165,7 +165,16 @@ export const stripeApiKeyRotationFactory: TRotationFactory<
) => {
if (!credentials?.length) return callback();
- for (const { keyId } of credentials) {
+ // The published key is retired last. A failure part way through aborts the delete, so retiring
+ // it first would leave the rotation row and its mapped secret in place pointing at a key that
+ // is on its way out, which is an outage until the operator retries.
+ const { activeIndex } = secretRotation;
+ const retirementOrder = [
+ ...credentials.filter((_, index) => index !== activeIndex),
+ ...credentials.filter((_, index) => index === activeIndex)
+ ];
+
+ for (const { keyId } of retirementOrder) {
// eslint-disable-next-line no-await-in-loop
await $retireKey(keyId);
}