Skip to content

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

feat(app-connections): list Stripe API keys without exposing secrets

Calvin132f52070f79
diff --git a/backend/src/server/routes/v1/app-connection-routers/stripe-connection-router.ts b/backend/src/server/routes/v1/app-connection-routers/stripe-connection-router.ts
index 56c520c355..ab1b270292 100644
--- a/backend/src/server/routes/v1/app-connection-routers/stripe-connection-router.ts
+++ b/backend/src/server/routes/v1/app-connection-routers/stripe-connection-router.ts
@@ -1,9 +1,14 @@
+import { z } from "zod";
+
+import { readLimit } from "@app/server/config/rateLimiter";
+import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
import { AppConnection } from "@app/services/app-connection/app-connection-enums";
import {
CreateStripeConnectionSchema,
SanitizedStripeConnectionSchema,
UpdateStripeConnectionSchema
} from "@app/services/app-connection/stripe";
+import { AuthMode } from "@app/services/auth/auth-type";
import { registerAppConnectionEndpoints } from "./app-connection-endpoints";
@@ -15,4 +20,42 @@ export const registerStripeConnectionRouter = async (server: FastifyZodProvider)
createSchema: CreateStripeConnectionSchema,
updateSchema: UpdateStripeConnectionSchema
});
+
+ // The below endpoints are not exposed and for Infisical App use
+ server.route({
+ method: "GET",
+ url: `/:connectionId/api-keys`,
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ operationId: "listStripeApiKeys",
+ params: z.object({
+ connectionId: z.string().uuid()
+ }),
+ response: {
+ 200: z.object({
+ // An allowlist, deliberately. Stripe's own list response carries every key's plaintext
+ // secret, so a passthrough schema here would ship them to the browser.
+ apiKeys: z
+ .object({
+ id: z.string(),
+ name: z.string(),
+ status: z.string(),
+ permissions: z.string().array(),
+ connectPermissions: z.string().array()
+ })
+ .array()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.OAUTH]),
+ handler: async (req) => {
+ const { connectionId } = req.params;
+
+ const apiKeys = await server.services.appConnection.stripe.listApiKeys(connectionId, req.permission);
+
+ return { apiKeys };
+ }
+ });
};
diff --git a/backend/src/services/app-connection/app-connection-service.ts b/backend/src/services/app-connection/app-connection-service.ts
index b4fd93297e..e5a58cb53b 100644
--- a/backend/src/services/app-connection/app-connection-service.ts
+++ b/backend/src/services/app-connection/app-connection-service.ts
@@ -181,7 +181,7 @@ import { snowflakeConnectionService } from "./snowflake/snowflake-connection-ser
import { ValidateSpaceliftConnectionCredentialsSchema } from "./spacelift";
import { spaceliftConnectionService } from "./spacelift/spacelift-connection-service";
import { ValidateSshConnectionCredentialsSchema } from "./ssh";
-import { ValidateStripeConnectionCredentialsSchema } from "./stripe";
+import { stripeConnectionService, ValidateStripeConnectionCredentialsSchema } from "./stripe";
import { ValidateSupabaseConnectionCredentialsSchema } from "./supabase";
import { supabaseConnectionService } from "./supabase/supabase-connection-service";
import { ValidateTeamCityConnectionCredentialsSchema } from "./teamcity";
@@ -1413,6 +1413,7 @@ export const appConnectionServiceFactory = ({
bitbucket: bitbucketConnectionService(connectAppConnectionById),
checkly: checklyConnectionService(connectAppConnectionById),
supabase: supabaseConnectionService(connectAppConnectionById),
+ stripe: stripeConnectionService(connectAppConnectionById),
rundeck: rundeckConnectionService(connectAppConnectionById),
digitalOcean: digitalOceanAppPlatformConnectionService(connectAppConnectionById),
netlify: netlifyConnectionService(connectAppConnectionById),
diff --git a/backend/src/services/app-connection/stripe/index.ts b/backend/src/services/app-connection/stripe/index.ts
index 28ad524180..b0533624cb 100644
--- a/backend/src/services/app-connection/stripe/index.ts
+++ b/backend/src/services/app-connection/stripe/index.ts
@@ -1,3 +1,5 @@
export * from "./stripe-connection-enums";
+export * from "./stripe-connection-public-client";
export * from "./stripe-connection-schemas";
+export * from "./stripe-connection-service";
export * from "./stripe-connection-types";
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 73013baa4e..263bec6306 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
@@ -1,9 +1,12 @@
+/* eslint-disable no-await-in-loop */
import crypto from "node:crypto";
-import { AxiosError, AxiosRequestConfig } from "axios";
+import { AxiosError, AxiosRequestConfig, AxiosResponse } from "axios";
import { getConfig } from "@app/lib/config/env";
+import { request } from "@app/lib/config/request";
import { BadRequestError, InternalServerError } from "@app/lib/errors";
+import { logger } from "@app/lib/logger";
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.
@@ -67,3 +70,51 @@ export const throwStripeApiKeyManagementError = (accountId: string, error: unkno
`If the Infisical app was removed from this Stripe account, reinstall it and reconnect.`
});
};
+
+export type TStripeApiKeyListItem = {
+ id: string;
+ name?: string | null;
+ status?: string | null;
+ permissions?: string[] | null;
+ connect_permissions?: string[] | null;
+};
+
+type TStripeApiKeyListResponse = {
+ data?: TStripeApiKeyListItem[];
+ next_page_url?: string | null;
+};
+
+const STRIPE_LIST_PAGE_SIZE = 100;
+
+// Stripe rejects limit=200 with "The maximum page limit is 100", so this is the largest page it
+// serves. The page cap is a runaway guard, not an expected bound.
+const STRIPE_LIST_MAX_PAGES = 50;
+
+export const listStripeApiKeys = async (accountId: string): Promise<TStripeApiKeyListItem[]> => {
+ const config = getStripePlatformRequestConfig(accountId);
+ const keys: TStripeApiKeyListItem[] = [];
+
+ let url: string | undefined = `${STRIPE_API_KEYS_URL}?limit=${STRIPE_LIST_PAGE_SIZE}`;
+ let pages = 0;
+
+ while (url && pages < STRIPE_LIST_MAX_PAGES) {
+ // The explicit AxiosResponse annotation breaks a circular type-inference error TS raises when a
+ // loop variable (url) is both an argument to this generic call and reassigned from its result.
+ const response: AxiosResponse<TStripeApiKeyListResponse> = await request.get<TStripeApiKeyListResponse>(
+ url,
+ config
+ );
+
+ keys.push(...(response.data?.data ?? []));
+ url = response.data?.next_page_url ?? undefined;
+ pages += 1;
+ }
+
+ if (url) {
+ logger.warn(
+ `listStripeApiKeys: stopped after ${STRIPE_LIST_MAX_PAGES} pages for account ${accountId}, the list is truncated`
+ );
+ }
+
+ return keys;
+};
diff --git a/backend/src/services/app-connection/stripe/stripe-connection-service.test.ts b/backend/src/services/app-connection/stripe/stripe-connection-service.test.ts
new file mode 100644
index 0000000000..0324d8a9f5
--- /dev/null
+++ b/backend/src/services/app-connection/stripe/stripe-connection-service.test.ts
@@ -0,0 +1,77 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const { getMock } = vi.hoisted(() => ({ getMock: vi.fn() }));
+
+vi.mock("@app/lib/config/env", () => ({
+ getConfig: () => ({ INF_APP_CONNECTION_STRIPE_SECRET_KEY: "sk_test_platform" })
+}));
+vi.mock("@app/lib/config/request", () => ({
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-call
+ request: { get: (...args: unknown[]) => (getMock 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 { stripeConnectionService } from "./stripe-connection-service";
+
+const keyPage = (id: string, next?: string) => ({
+ data: {
+ data: [
+ {
+ id,
+ name: `key-${id}`,
+ status: "active",
+ permissions: ["charge_read"],
+ connect_permissions: [],
+ // Stripe really does return this, in full, for every key.
+ secret_key: { token: `rk_test_${id}_full_plaintext_secret`, secret_token_redacted: "rk_test_...ab12" }
+ }
+ ],
+ next_page_url: next ?? null
+ }
+});
+
+const makeService = () =>
+ stripeConnectionService(
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument
+ vi.fn(async () => ({ credentials: { accountId: "acct_123" } })) as any
+ );
+
+describe("stripeConnectionService.listApiKeys", () => {
+ beforeEach(() => getMock.mockReset());
+
+ it("never returns the plaintext secret Stripe includes in every list item", async () => {
+ getMock.mockResolvedValueOnce(keyPage("mk_1"));
+
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument
+ const keys = await makeService().listApiKeys("connection-id", {} as any);
+
+ expect(keys).toEqual([
+ {
+ id: "mk_1",
+ name: "key-mk_1",
+ status: "active",
+ permissions: ["charge_read"],
+ connectPermissions: []
+ }
+ ]);
+ expect(JSON.stringify(keys)).not.toContain("plaintext_secret");
+ expect(JSON.stringify(keys)).not.toContain("secret_key");
+ });
+
+ it("follows next_page_url instead of returning only the first page", async () => {
+ getMock
+ .mockResolvedValueOnce(keyPage("mk_1", "https://api.stripe.com/v2/iam/api_keys?page=2"))
+ .mockResolvedValueOnce(keyPage("mk_2"));
+
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument
+ const keys = await makeService().listApiKeys("connection-id", {} as any);
+
+ expect(keys.map((key) => key.id)).toEqual(["mk_1", "mk_2"]);
+ expect(getMock).toHaveBeenCalledTimes(2);
+ expect(getMock.mock.calls[0][0]).toContain("limit=100");
+ expect(getMock.mock.calls[1][0]).toBe("https://api.stripe.com/v2/iam/api_keys?page=2");
+ });
+});
diff --git a/backend/src/services/app-connection/stripe/stripe-connection-service.ts b/backend/src/services/app-connection/stripe/stripe-connection-service.ts
new file mode 100644
index 0000000000..504c4cfb73
--- /dev/null
+++ b/backend/src/services/app-connection/stripe/stripe-connection-service.ts
@@ -0,0 +1,44 @@
+import { OrgServiceActor } from "@app/lib/types";
+
+import { AppConnection } from "../app-connection-enums";
+import { listStripeApiKeys, throwStripeApiKeyManagementError } from "./stripe-connection-public-client";
+import { TStripeConnection } from "./stripe-connection-types";
+
+type TGetAppConnectionFunc = (
+ app: AppConnection,
+ connectionId: string,
+ actor: OrgServiceActor
+) => Promise<TStripeConnection>;
+
+export type TStripeApiKeySummary = {
+ id: string;
+ name: string;
+ status: string;
+ permissions: string[];
+ connectPermissions: string[];
+};
+
+export const stripeConnectionService = (getAppConnection: TGetAppConnectionFunc) => {
+ const listApiKeys = async (connectionId: string, actor: OrgServiceActor): Promise<TStripeApiKeySummary[]> => {
+ const appConnection = await getAppConnection(AppConnection.Stripe, connectionId, actor);
+ const { accountId } = appConnection.credentials;
+
+ try {
+ const keys = await listStripeApiKeys(accountId);
+
+ // Stripe returns secret_key.token, in full plaintext, for every key in the account. Mapping to
+ // an explicit shape here is what keeps it out of the HTTP response.
+ return keys.map((key) => ({
+ id: key.id,
+ name: key.name ?? "",
+ status: key.status ?? "",
+ permissions: key.permissions ?? [],
+ connectPermissions: key.connect_permissions ?? []
+ }));
+ } catch (error) {
+ return throwStripeApiKeyManagementError(accountId, error);
+ }
+ };
+
+ return { listApiKeys };
+};