Skip to content

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

refactor(app-connections): extract shared Stripe request client

Calvin05d812a3c8c2
diff --git a/backend/src/services/app-connection/stripe/stripe-connection-fns.ts b/backend/src/services/app-connection/stripe/stripe-connection-fns.ts
index 93b8087d9a..fd84a3853b 100644
--- a/backend/src/services/app-connection/stripe/stripe-connection-fns.ts
+++ b/backend/src/services/app-connection/stripe/stripe-connection-fns.ts
@@ -2,34 +2,25 @@ import { AxiosError } from "axios";
import { getConfig } from "@app/lib/config/env";
import { request } from "@app/lib/config/request";
-import { BadRequestError, InternalServerError } from "@app/lib/errors";
+import { BadRequestError } from "@app/lib/errors";
import { AppConnection } from "@app/services/app-connection/app-connection-enums";
import { IntegrationUrls } from "@app/services/integration-auth/integration-list";
import { StripeConnectionMethod } from "./stripe-connection-enums";
+import {
+ getStripePlatformRequestConfig,
+ getStripeSecretKey,
+ STRIPE_API_KEYS_URL,
+ throwStripeApiKeyManagementError
+} from "./stripe-connection-public-client";
import { TStripeConnectionConfig } from "./stripe-connection-types";
-// The Managed API Keys API is in private preview and is only served under a preview API version.
-const STRIPE_PREVIEW_API_VERSION = "2026-08-26.preview";
-
type TStripeOAuthTokenResponse = {
// The initial exchange names the account stripe_user_id; the refresh grant names it account_id.
stripe_user_id?: string;
account_id?: string;
};
-const getStripeSecretKey = () => {
- const { INF_APP_CONNECTION_STRIPE_SECRET_KEY } = getConfig();
-
- if (!INF_APP_CONNECTION_STRIPE_SECRET_KEY) {
- throw new InternalServerError({
- message: "Stripe is not configured on this instance. Set the Stripe App Connection credentials to enable it."
- });
- }
-
- return INF_APP_CONNECTION_STRIPE_SECRET_KEY;
-};
-
export const getStripeConnectionListItem = () => {
const { INF_APP_CONNECTION_STRIPE_OAUTH_CLIENT_ID, INF_APP_CONNECTION_STRIPE_OAUTH_AUTHORIZE_URL } = getConfig();
@@ -90,25 +81,9 @@ const exchangeStripeOAuthCode = async (code: string): Promise<string> => {
*/
const assertCanManageApiKeys = async (accountId: string) => {
try {
- await request.get(`${IntegrationUrls.STRIPE_API_URL}/v2/iam/api_keys`, {
- auth: { username: getStripeSecretKey(), password: "" },
- headers: {
- "Stripe-Version": STRIPE_PREVIEW_API_VERSION,
- "Stripe-Context": accountId
- }
- });
+ await request.get(STRIPE_API_KEYS_URL, getStripePlatformRequestConfig(accountId));
} catch (error) {
- if (error instanceof AxiosError) {
- const message = (error.response?.data as { error?: { message?: string } } | undefined)?.error?.message;
-
- throw new BadRequestError({
- message: `Infisical cannot manage API keys on Stripe account '${accountId}'. Stripe returned ${
- error.response?.status ?? "no status"
- }: ${message ?? error.message}`
- });
- }
-
- throw error;
+ throwStripeApiKeyManagementError(accountId, error);
}
};
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
new file mode 100644
index 0000000000..e836455693
--- /dev/null
+++ b/backend/src/services/app-connection/stripe/stripe-connection-public-client.test.ts
@@ -0,0 +1,67 @@
+import { AxiosError } from "axios";
+import { describe, expect, it, vi } from "vitest";
+
+vi.mock("@app/lib/config/env", () => ({
+ getConfig: () => ({ INF_APP_CONNECTION_STRIPE_SECRET_KEY: "sk_test_platform" })
+}));
+
+// eslint-disable-next-line import/first
+import {
+ getStripeErrorMessage,
+ getStripeErrorStatus,
+ getStripeMerchantRequestConfig,
+ getStripePlatformRequestConfig,
+ STRIPE_PREVIEW_API_VERSION,
+ withIdempotencyKey
+} from "./stripe-connection-public-client";
+
+const axiosErrorWith = (status: number, data: unknown) =>
+ new AxiosError("Request failed", "ERR_BAD_REQUEST", undefined, undefined, {
+ status,
+ statusText: "",
+ headers: {},
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment
+ config: {} as any,
+ data
+ });
+
+describe("stripe public client", () => {
+ it("authenticates as the platform and names the account", () => {
+ const config = getStripePlatformRequestConfig("acct_123");
+
+ expect(config.auth).toEqual({ username: "sk_test_platform", password: "" });
+ expect(config.headers).toEqual({
+ "Stripe-Version": STRIPE_PREVIEW_API_VERSION,
+ "Stripe-Context": "acct_123"
+ });
+ });
+
+ it("authenticates as a merchant key without context or preview version", () => {
+ const config = getStripeMerchantRequestConfig("rk_test_merchant");
+
+ expect(config.auth).toEqual({ username: "rk_test_merchant", password: "" });
+ expect(config.headers).toBeUndefined();
+ });
+
+ it("adds an idempotency key without dropping existing headers", () => {
+ const config = withIdempotencyKey(getStripePlatformRequestConfig("acct_123"));
+
+ expect(config.headers?.["Stripe-Context"]).toBe("acct_123");
+ expect(config.headers?.["Idempotency-Key"]).toMatch(
+ /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/
+ );
+ });
+
+ it("reads Stripe's own error message when there is one", () => {
+ const error = axiosErrorWith(400, { error: { message: "Invalid permissions: nope" } });
+
+ expect(getStripeErrorMessage(error)).toBe("Invalid permissions: nope");
+ expect(getStripeErrorStatus(error)).toBe(400);
+ });
+
+ it("falls back to the axios message and handles plain errors", () => {
+ expect(getStripeErrorMessage(axiosErrorWith(500, undefined))).toBe("Request failed");
+ expect(getStripeErrorMessage(new Error("socket hang up"))).toBe("socket hang up");
+ expect(getStripeErrorStatus(new Error("socket hang up"))).toBeUndefined();
+ });
+});
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
new file mode 100644
index 0000000000..73013baa4e
--- /dev/null
+++ b/backend/src/services/app-connection/stripe/stripe-connection-public-client.ts
@@ -0,0 +1,69 @@
+import crypto from "node:crypto";
+
+import { AxiosError, AxiosRequestConfig } from "axios";
+
+import { getConfig } from "@app/lib/config/env";
+import { BadRequestError, InternalServerError } from "@app/lib/errors";
+import { IntegrationUrls } from "@app/services/integration-auth/integration-list";
+
+// The Managed API Keys API is in private preview and is only served under a preview API version.
+export const STRIPE_PREVIEW_API_VERSION = "2026-08-26.preview";
+
+export const STRIPE_API_KEYS_URL = `${IntegrationUrls.STRIPE_API_URL}/v2/iam/api_keys`;
+
+export const getStripeSecretKey = () => {
+ const { INF_APP_CONNECTION_STRIPE_SECRET_KEY } = getConfig();
+
+ if (!INF_APP_CONNECTION_STRIPE_SECRET_KEY) {
+ throw new InternalServerError({
+ message: "Stripe is not configured on this instance. Set the Stripe App Connection credentials to enable it."
+ });
+ }
+
+ return INF_APP_CONNECTION_STRIPE_SECRET_KEY;
+};
+
+/** Infisical acting on a customer's account: our own key, with Stripe-Context naming the account. */
+export const getStripePlatformRequestConfig = (accountId: string): AxiosRequestConfig => ({
+ auth: { username: getStripeSecretKey(), password: "" },
+ headers: {
+ "Stripe-Version": STRIPE_PREVIEW_API_VERSION,
+ "Stripe-Context": accountId
+ }
+});
+
+/** A rotated merchant key acting as itself. It is not the platform, so it carries neither header. */
+export const getStripeMerchantRequestConfig = (apiKey: string): AxiosRequestConfig => ({
+ auth: { username: apiKey, password: "" }
+});
+
+export const withIdempotencyKey = (config: AxiosRequestConfig): AxiosRequestConfig => ({
+ ...config,
+ headers: { ...config.headers, "Idempotency-Key": crypto.randomUUID() }
+});
+
+export const getStripeErrorMessage = (error: unknown): string => {
+ if (error instanceof AxiosError) {
+ const message = (error.response?.data as { error?: { message?: string } } | undefined)?.error?.message;
+
+ return typeof message === "string" ? message : error.message;
+ }
+
+ return (error as Error)?.message ?? "Unknown error";
+};
+
+export const getStripeErrorStatus = (error: unknown): number | undefined =>
+ error instanceof AxiosError ? error.response?.status : 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.
+ */
+export const throwStripeApiKeyManagementError = (accountId: string, error: unknown): never => {
+ throw new BadRequestError({
+ message:
+ `Infisical cannot manage API keys on Stripe account '${accountId}'. ` +
+ `Stripe returned ${getStripeErrorStatus(error) ?? "no status"}: ${getStripeErrorMessage(error)}. ` +
+ `If the Infisical app was removed from this Stripe account, reinstall it and reconnect.`
+ });
+};