Skip to content

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

fix(secret-rotation): stop stripe key rotation wedging on a double expire

Calvinc0079ccf3fb9
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 45cb161310..4423dfabd0 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
@@ -183,6 +183,31 @@ describe("stripeApiKeyRotationFactory", () => {
).resolves.toBeDefined();
});
+ it("completes a rotation when the old key is already gone from Stripe, without ever calling expire on it", async () => {
+ // A double expire's response has never been observed, so this drives the fix through the
+ // existence check (a 404 on retrieve) rather than assuming a 404 on a second expire call.
+ 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 new Error("expire must not be called for a key the existence check already found gone");
+ }
+ 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();
+
+ expect(expireCalls("mk_old")).toHaveLength(0);
+ expect(callback).toHaveBeenCalled();
+ });
+
it("revokeCredentials returns early without contacting Stripe when there are no credentials", async () => {
const callback = vi.fn(async () => "done");
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 7c359999f5..1e492b8fb0 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
@@ -28,8 +28,6 @@ import {
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
@@ -46,8 +44,28 @@ export const stripeApiKeyRotationFactory: TRotationFactory<
// 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);
- /** A 404 means the key is already gone; anything else is handed back for the caller to report. */
+ /** No 404 on a double expire has ever been observed, so retiring a key twice can't be trusted to look
+ * like the first expire. Checking existence first sidesteps the question: a key that is already
+ * gone is retired either way, and a key that still exists gets the expire call as before.
+ */
+ const $keyExists = async (keyId: string): Promise<boolean> => {
+ try {
+ await request.get(`${STRIPE_API_KEYS_URL}/${keyId}`, getStripePlatformRequestConfig(accountId));
+ return true;
+ } catch (error) {
+ if (getStripeErrorStatus(error) === 404) return false;
+
+ throw error;
+ }
+ };
+
const $tryRetireKey = async (keyId: string): Promise<{ retired: true } | { retired: false; error: unknown }> => {
+ try {
+ if (!(await $keyExists(keyId))) return { retired: true };
+ } catch (error) {
+ return { retired: false, error };
+ }
+
try {
await request.post(
`${STRIPE_API_KEYS_URL}/${keyId}/expire`,
@@ -85,7 +103,7 @@ export const stripeApiKeyRotationFactory: TRotationFactory<
await $retireKey(keyId);
} catch (cleanupError) {
throw new BadRequestError({
- message: `${getErrorMessage(actionError)} The newly created Stripe API key ${keyId} could not be expired and may need to be removed manually: ${getErrorMessage(cleanupError)}`
+ message: `${getStripeErrorMessage(actionError)} The newly created Stripe API key ${keyId} could not be expired and may need to be removed manually: ${getStripeErrorMessage(cleanupError)}`
});
}
diff --git a/backend/src/services/app-connection/stripe/stripe-connection-public-client.test.ts b/backend/src/services/app-connection/stripe/stripe-connection-public-client.test.ts
index e836455693..a10d2c46d3 100644
--- a/backend/src/services/app-connection/stripe/stripe-connection-public-client.test.ts
+++ b/backend/src/services/app-connection/stripe/stripe-connection-public-client.test.ts
@@ -5,6 +5,9 @@ vi.mock("@app/lib/config/env", () => ({
getConfig: () => ({ INF_APP_CONNECTION_STRIPE_SECRET_KEY: "sk_test_platform" })
}));
+// eslint-disable-next-line import/first
+import { InternalServerError } from "@app/lib/errors";
+
// eslint-disable-next-line import/first
import {
getStripeErrorMessage,
@@ -12,6 +15,7 @@ import {
getStripeMerchantRequestConfig,
getStripePlatformRequestConfig,
STRIPE_PREVIEW_API_VERSION,
+ throwStripeApiKeyManagementError,
withIdempotencyKey
} from "./stripe-connection-public-client";
@@ -64,4 +68,16 @@ describe("stripe public client", () => {
expect(getStripeErrorMessage(new Error("socket hang up"))).toBe("socket hang up");
expect(getStripeErrorStatus(new Error("socket hang up"))).toBeUndefined();
});
+
+ it("wraps an axios error as a Stripe management failure", () => {
+ expect(() =>
+ throwStripeApiKeyManagementError("acct_123", axiosErrorWith(403, { error: { message: "app removed" } }))
+ ).toThrow(/Infisical cannot manage API keys on Stripe account 'acct_123'/);
+ });
+
+ it("rethrows a non-axios error as itself instead of blaming Stripe or the installed app", () => {
+ const localError = new InternalServerError({ message: "Stripe is not configured on this instance." });
+
+ expect(() => throwStripeApiKeyManagementError("acct_123", localError)).toThrow(localError);
+ });
});
diff --git a/backend/src/services/app-connection/stripe/stripe-connection-public-client.ts b/backend/src/services/app-connection/stripe/stripe-connection-public-client.ts
index 938f2c5955..93dedc7e32 100644
--- a/backend/src/services/app-connection/stripe/stripe-connection-public-client.ts
+++ b/backend/src/services/app-connection/stripe/stripe-connection-public-client.ts
@@ -61,8 +61,14 @@ export const getStripeErrorStatus = (error: unknown): number | undefined =>
/**
* Nothing proactively notices that a customer uninstalled the app, because the connection stores no
* tokens, so it arrives here as a 403. The remedy is offered conditionally rather than asserted.
+ *
+ * Only an Axios error is actually a response from Stripe. Anything else, eg a local
+ * misconfiguration like a missing platform key, gets rethrown as itself rather than reworded into
+ * a message that blames Stripe or the installed app for something neither caused.
*/
export const throwStripeApiKeyManagementError = (accountId: string, error: unknown): never => {
+ if (!(error instanceof AxiosError)) throw error;
+
throw new BadRequestError({
message:
`Infisical cannot manage API keys on Stripe account '${accountId}'. ` +
@@ -90,6 +96,18 @@ const STRIPE_LIST_PAGE_SIZE = 100;
// serves. The page cap is a runaway guard, not an expected bound.
const STRIPE_LIST_MAX_PAGES = 50;
+// Stripe's list response carries secret_key.token, in full plaintext, for every key in the account.
+// TStripeApiKeyListItem omits it only at the type level, so rebuilding each item as a fresh object
+// literal is what actually keeps the raw response object, and the secret it carries, from leaving
+// this function. Downstream callers strip it again on their own responses; this is defense in depth.
+const sanitizeApiKeyListItem = (item: TStripeApiKeyListItem): TStripeApiKeyListItem => ({
+ id: item.id,
+ name: item.name,
+ status: item.status,
+ permissions: item.permissions,
+ connect_permissions: item.connect_permissions
+});
+
export const listStripeApiKeys = async (accountId: string): Promise<TStripeApiKeyListItem[]> => {
const config = getStripePlatformRequestConfig(accountId);
const keys: TStripeApiKeyListItem[] = [];
@@ -105,7 +123,7 @@ export const listStripeApiKeys = async (accountId: string): Promise<TStripeApiKe
config
);
- keys.push(...(response.data?.data ?? []));
+ keys.push(...(response.data?.data ?? []).map(sanitizeApiKeyListItem));
const nextPageUrl = response.data?.next_page_url ?? undefined;