Skip to content

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

fix(secret-rotation): confirm the Stripe install before each operation

Calvin8ccdbd2d94e2
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 50387b20ad..48e0c59200 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
@@ -3,9 +3,10 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
import { TSecretRotationV2Raw } from "@app/ee/services/secret-rotation-v2/secret-rotation-v2-types";
-const { getMock, postMock } = vi.hoisted(() => ({
+const { getMock, postMock, authorizeMock } = vi.hoisted(() => ({
getMock: vi.fn<(url: string, config?: unknown) => Promise<unknown>>(),
- postMock: vi.fn<(url: string, body?: unknown, config?: unknown) => Promise<unknown>>()
+ postMock: vi.fn<(url: string, body?: unknown, config?: unknown) => Promise<unknown>>(),
+ authorizeMock: vi.fn<(connectionId: string) => Promise<void>>()
}));
vi.mock("@app/lib/config/env", () => ({
@@ -14,6 +15,9 @@ vi.mock("@app/lib/config/env", () => ({
vi.mock("@app/lib/config/request", () => ({
request: { get: getMock, post: postMock }
}));
+vi.mock("@app/services/app-connection/stripe/stripe-connection-fns", () => ({
+ assertStripeConnectionAuthorized: authorizeMock
+}));
vi.mock("@app/lib/logger", () => ({
logger: { error: vi.fn(), info: vi.fn(), warn: vi.fn(), debug: vi.fn() }
}));
@@ -40,7 +44,8 @@ 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.
+// The factory hands appConnectionDAL and kmsService to the authorization check, which is mocked, so
+// none of these are reached.
const UNUSED_DEPENDENCIES = [{}, {}, {}, {}] as unknown as [
Parameters<typeof stripeApiKeyRotationFactory>[1],
Parameters<typeof stripeApiKeyRotationFactory>[2],
@@ -146,6 +151,8 @@ describe("stripeApiKeyRotationFactory", () => {
createBody = undefined;
getMock.mockReset();
postMock.mockReset();
+ authorizeMock.mockReset();
+ authorizeMock.mockResolvedValue(undefined);
commit.mockClear();
commitWithoutCredentials.mockClear();
});
@@ -162,6 +169,31 @@ describe("stripeApiKeyRotationFactory", () => {
expect(createBody?.public_key.pem_key.data).toContain("BEGIN PUBLIC KEY");
});
+ it("confirms the connection is still authorized before acting on the account with the app key", async () => {
+ mockStripe();
+
+ await makeFactory().issueCredentials(commit);
+
+ const { headers } = postMock.mock.calls[0][2] as { headers: Record<string, string> };
+
+ expect(authorizeMock).toHaveBeenCalledWith("connection-id", {}, {});
+ expect(authorizeMock.mock.invocationCallOrder[0]).toBeLessThan(postMock.mock.invocationCallOrder[0]);
+ expect(headers.Authorization).toBe("Bearer sk_test_app");
+ expect(headers["Stripe-Context"]).toBe("acct_123");
+ });
+
+ it.each([
+ { operation: "issue", run: () => makeFactory().issueCredentials(commit) },
+ { operation: "rotate", run: () => makeFactory().rotateCredentials(OLD_KEY, commit, OLD_KEY) },
+ { operation: "revoke", run: () => makeFactory().revokeCredentials([OLD_KEY], commitWithoutCredentials) }
+ ])("does not touch Stripe keys on $operation once the app was uninstalled", async ({ run }) => {
+ mockStripe();
+ authorizeMock.mockRejectedValue(new Error("Infisical is no longer authorized"));
+
+ await expect(run()).rejects.toThrow("Infisical is no longer authorized");
+ expect(calls).toEqual([]);
+ });
+
// The key exists in Stripe before the row does, so both failure points after create have to
// take it with them.
it.each([
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 61fd77eef4..13e497e4f1 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
@@ -8,6 +8,7 @@ import {
} 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 { assertStripeConnectionAuthorized } from "@app/services/app-connection/stripe/stripe-connection-fns";
import {
getStripeAppRequestConfig,
getStripeErrorMessage,
@@ -31,7 +32,7 @@ const STRIPE_KEY_NAME_MAX_LENGTH = 100;
export const stripeApiKeyRotationFactory: TRotationFactory<
TStripeApiKeyRotationWithConnection,
TStripeApiKeyRotationGeneratedCredentials
-> = (secretRotation) => {
+> = (secretRotation, appConnectionDAL, kmsService) => {
const {
connection,
parameters: { permissions, connectPermissions },
@@ -40,6 +41,10 @@ export const stripeApiKeyRotationFactory: TRotationFactory<
const { accountId } = connection.credentials;
+ // Runs once at the start of each operation, not per request, so the cleanup a failed operation
+ // does (expiring a key it just created) never fails on authorization half way through.
+ const $assertAuthorized = () => assertStripeConnectionAuthorized(connection.id, appConnectionDAL, kmsService);
+
// 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);
@@ -164,6 +169,8 @@ export const stripeApiKeyRotationFactory: TRotationFactory<
const issueCredentials: TRotationFactoryIssueCredentials<TStripeApiKeyRotationGeneratedCredentials> = async (
callback
) => {
+ await $assertAuthorized();
+
const credentials = await $createApiKey();
return $retireOnFailure(credentials.keyId, () => callback(credentials));
@@ -175,6 +182,8 @@ export const stripeApiKeyRotationFactory: TRotationFactory<
) => {
if (!credentials?.length) return callback();
+ await $assertAuthorized();
+
// 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.
@@ -195,6 +204,8 @@ export const stripeApiKeyRotationFactory: TRotationFactory<
credentialsToRevoke,
callback
) => {
+ await $assertAuthorized();
+
const newCredentials = await $createApiKey();
// Retire before committing, so a failure leaves Postgres and Stripe agreeing with each other and
diff --git a/backend/src/services/app-connection/app-connection-service.ts b/backend/src/services/app-connection/app-connection-service.ts
index 5c49e4f0a5..be8bc38597 100644
--- a/backend/src/services/app-connection/app-connection-service.ts
+++ b/backend/src/services/app-connection/app-connection-service.ts
@@ -181,7 +181,8 @@ import { snowflakeConnectionService } from "./snowflake/snowflake-connection-ser
import { ValidateSpaceliftConnectionCredentialsSchema } from "./spacelift";
import { spaceliftConnectionService } from "./spacelift/spacelift-connection-service";
import { ValidateSshConnectionCredentialsSchema } from "./ssh";
-import { stripeConnectionService, ValidateStripeConnectionCredentialsSchema } from "./stripe";
+import { ValidateStripeConnectionCredentialsSchema } from "./stripe";
+import { stripeConnectionService } from "./stripe/stripe-connection-service";
import { ValidateSupabaseConnectionCredentialsSchema } from "./supabase";
import { supabaseConnectionService } from "./supabase/supabase-connection-service";
import { ValidateTeamCityConnectionCredentialsSchema } from "./teamcity";
@@ -1422,7 +1423,7 @@ export const appConnectionServiceFactory = ({
bitbucket: bitbucketConnectionService(connectAppConnectionById),
checkly: checklyConnectionService(connectAppConnectionById),
supabase: supabaseConnectionService(connectAppConnectionById),
- stripe: stripeConnectionService(connectAppConnectionById),
+ stripe: stripeConnectionService(connectAppConnectionById, appConnectionDAL, kmsService),
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 b0533624cb..9f9f9e6a8f 100644
--- a/backend/src/services/app-connection/stripe/index.ts
+++ b/backend/src/services/app-connection/stripe/index.ts
@@ -1,5 +1,4 @@
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-fns.test.ts b/backend/src/services/app-connection/stripe/stripe-connection-fns.test.ts
new file mode 100644
index 0000000000..8a28667760
--- /dev/null
+++ b/backend/src/services/app-connection/stripe/stripe-connection-fns.test.ts
@@ -0,0 +1,136 @@
+import { AxiosError } from "axios";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const { postMock, decryptMock, encryptMock } = vi.hoisted(() => ({
+ postMock: vi.fn<(url: string, body?: unknown, config?: unknown) => Promise<unknown>>(),
+ decryptMock: vi.fn<() => Promise<unknown>>(),
+ encryptMock: vi.fn(async ({ credentials }: { credentials: unknown }) => ({ encrypted: credentials }))
+}));
+
+vi.mock("@app/lib/config/env", () => ({
+ getConfig: () => ({ INF_APP_CONNECTION_STRIPE_SECRET_KEY: "sk_test_app" })
+}));
+vi.mock("@app/lib/config/request", () => ({
+ request: { post: postMock, get: vi.fn() }
+}));
+vi.mock("@app/services/app-connection/app-connection-fns", () => ({
+ decryptAppConnectionCredentials: decryptMock,
+ encryptAppConnectionCredentials: encryptMock
+}));
+
+// eslint-disable-next-line import/first
+import { AppConnection } from "../app-connection-enums";
+// eslint-disable-next-line import/first
+import { assertStripeConnectionAuthorized } from "./stripe-connection-fns";
+
+const storedCredentials = (overrides: Record<string, unknown> = {}) => ({
+ accountId: "acct_123",
+ refreshToken: "rt_old",
+ ...overrides
+});
+
+const appConnectionDAL = {
+ findById: vi.fn(async () => ({
+ id: "connection-id",
+ app: AppConnection.Stripe,
+ orgId: "org-id",
+ projectId: null,
+ encryptedCredentials: Buffer.from("")
+ })),
+ updateById: vi.fn(async () => ({}))
+};
+
+const authorize = () =>
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument
+ assertStripeConnectionAuthorized("connection-id", appConnectionDAL as any, {} as any);
+
+const oauthError = (status: number, error: string, description: string) =>
+ new AxiosError("Request failed", "ERR_BAD_REQUEST", undefined, undefined, {
+ status,
+ statusText: "",
+ headers: {},
+ config: {} as never,
+ data: { error, error_description: description }
+ });
+
+const invalidGrant = () => oauthError(400, "invalid_grant", "Refresh token revoked");
+
+const refreshed = (refreshToken: string, accountId = "acct_123") => ({
+ data: { access_token: "rk_unused", refresh_token: refreshToken, account_id: accountId }
+});
+
+const sentRefreshToken = (call: number) => (postMock.mock.calls[call][1] as URLSearchParams).get("refresh_token");
+
+describe("assertStripeConnectionAuthorized", () => {
+ beforeEach(() => {
+ postMock.mockReset();
+ decryptMock.mockReset();
+ encryptMock.mockClear();
+ appConnectionDAL.findById.mockClear();
+ appConnectionDAL.updateById.mockClear();
+ });
+
+ it("refreshes on every call and stores only the account and the new refresh token", async () => {
+ decryptMock.mockResolvedValue(storedCredentials());
+ postMock.mockResolvedValue(refreshed("rt_new"));
+
+ await authorize();
+ await authorize();
+
+ expect(postMock).toHaveBeenCalledTimes(2);
+ expect((postMock.mock.calls[0][1] as URLSearchParams).get("grant_type")).toBe("refresh_token");
+ expect(sentRefreshToken(0)).toBe("rt_old");
+ expect(encryptMock.mock.calls[0][0].credentials).toEqual({ accountId: "acct_123", refreshToken: "rt_new" });
+ expect(appConnectionDAL.updateById).toHaveBeenCalledWith("connection-id", expect.anything());
+ });
+
+ it("retries with the token a concurrent refresh stored when its own spent one is rejected", async () => {
+ decryptMock
+ .mockResolvedValueOnce(storedCredentials())
+ .mockResolvedValueOnce(storedCredentials({ refreshToken: "rt_raced" }));
+ postMock.mockRejectedValueOnce(invalidGrant()).mockResolvedValueOnce(refreshed("rt_after_race"));
+
+ await authorize();
+
+ expect(sentRefreshToken(1)).toBe("rt_raced");
+ expect(encryptMock.mock.calls[0][0].credentials).toEqual({ accountId: "acct_123", refreshToken: "rt_after_race" });
+ });
+
+ it("stays revoked after an uninstall, even when a concurrent refresh stored a newer token", async () => {
+ decryptMock
+ .mockResolvedValueOnce(storedCredentials())
+ .mockResolvedValueOnce(storedCredentials({ refreshToken: "rt_raced" }));
+ postMock.mockRejectedValue(invalidGrant());
+
+ await expect(authorize()).rejects.toThrow(/no longer authorized on Stripe account 'acct_123'/);
+ expect(appConnectionDAL.updateById).not.toHaveBeenCalled();
+ });
+
+ it("asks for a reinstall when the refresh token was revoked", async () => {
+ decryptMock.mockResolvedValue(storedCredentials());
+ postMock.mockRejectedValue(invalidGrant());
+
+ await expect(authorize()).rejects.toThrow(
+ /Infisical is no longer authorized on Stripe account 'acct_123': Refresh token revoked\. This happens when the Infisical app is uninstalled/
+ );
+ expect(postMock).toHaveBeenCalledTimes(1);
+ });
+
+ it("does not blame an uninstall for a Stripe outage", async () => {
+ decryptMock.mockResolvedValue(storedCredentials());
+ postMock.mockRejectedValue(oauthError(503, "api_error", "Service unavailable"));
+
+ await expect(authorize()).rejects.toThrow(
+ "Infisical could not confirm its access to Stripe account 'acct_123': Service unavailable"
+ );
+ expect(postMock).toHaveBeenCalledTimes(1);
+ });
+
+ it("refuses tokens Stripe issued for a different account", async () => {
+ decryptMock.mockResolvedValue(storedCredentials());
+ postMock.mockResolvedValue(refreshed("rt_other", "acct_other"));
+
+ await expect(authorize()).rejects.toThrow(/bound to 'acct_123'/);
+ expect(appConnectionDAL.updateById).not.toHaveBeenCalled();
+ });
+});
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 c1343700e0..d9fe003af1 100644
--- a/backend/src/services/app-connection/stripe/stripe-connection-fns.ts
+++ b/backend/src/services/app-connection/stripe/stripe-connection-fns.ts
@@ -2,10 +2,16 @@ import { AxiosError } from "axios";
import { getConfig } from "@app/lib/config/env";
import { request } from "@app/lib/config/request";
-import { BadRequestError } from "@app/lib/errors";
+import { BadRequestError, NotFoundError } from "@app/lib/errors";
import { AppConnection } from "@app/services/app-connection/app-connection-enums";
+import {
+ decryptAppConnectionCredentials,
+ encryptAppConnectionCredentials
+} from "@app/services/app-connection/app-connection-fns";
import { IntegrationUrls } from "@app/services/integration-auth/integration-list";
+import { TKmsServiceFactory } from "@app/services/kms/kms-service";
+import { TAppConnectionDALFactory } from "../app-connection-dal";
import { StripeConnectionMethod } from "./stripe-connection-enums";
import {
getStripeAppRequestConfig,
@@ -13,9 +19,10 @@ import {
STRIPE_API_KEYS_URL,
throwStripeApiKeyManagementError
} from "./stripe-connection-public-client";
-import { TStripeConnectionConfig } from "./stripe-connection-types";
+import { TStripeConnectionConfig, TStripeConnectionCredentials } from "./stripe-connection-types";
type TStripeOAuthTokenResponse = {
+ refresh_token?: string;
// The initial exchange names the account stripe_user_id; the refresh grant names it account_id.
stripe_user_id?: string;
account_id?: string;
@@ -36,29 +43,38 @@ export const getStripeConnectionListItem = () => {
};
};
+const requestStripeTokens = async (params: Record<string, string>) => {
+ const { data } = await request.post<TStripeOAuthTokenResponse>(
+ IntegrationUrls.STRIPE_TOKEN_URL,
+ new URLSearchParams(params),
+ {
+ auth: { username: getStripeSecretKey(), password: "" },
+ headers: { "Content-Type": "application/x-www-form-urlencoded" }
+ }
+ );
+
+ return data;
+};
+
+const getStripeOAuthErrorDescription = (error: AxiosError) =>
+ (error.response?.data as { error_description?: string } | undefined)?.error_description ?? error.message;
+
+const isStripeRefreshTokenRejected = (error: unknown) =>
+ error instanceof AxiosError && (error.response?.data as { error?: string } | undefined)?.error === "invalid_grant";
+
/**
- * Infisical authenticates as itself and names the customer with Stripe-Context, so the tokens this
- * exchange returns are never used. It runs because it is the only proof that the installer controls
- * the account they are claiming: a client-supplied account ID would be unverified.
+ * The exchange is also the only proof that the installer controls the account they are claiming: a
+ * client-supplied account ID would be unverified.
*/
-const exchangeStripeOAuthCode = async (code: string): Promise<string> => {
+const exchangeStripeOAuthCode = async (code: string): Promise<TStripeConnectionCredentials> => {
let data: TStripeOAuthTokenResponse;
try {
- ({ data } = await request.post<TStripeOAuthTokenResponse>(
- IntegrationUrls.STRIPE_TOKEN_URL,
- new URLSearchParams({ grant_type: "authorization_code", code }),
- {
- auth: { username: getStripeSecretKey(), password: "" },
- headers: { "Content-Type": "application/x-www-form-urlencoded" }
- }
- ));
+ data = await requestStripeTokens({ grant_type: "authorization_code", code });
} catch (error) {
if (error instanceof AxiosError) {
- const description = (error.response?.data as { error_description?: string } | undefined)?.error_description;
-
throw new BadRequestError({
- message: `Stripe rejected the app installation: ${description ?? error.message}`
+ message: `Stripe rejected the app installation: ${getStripeOAuthErrorDescription(error)}`
});
}
@@ -67,13 +83,14 @@ const exchangeStripeOAuthCode = async (code: string): Promise<string> => {
const accountId = data?.stripe_user_id ?? data?.account_id;
- if (!accountId) {
+ if (!accountId || !data.refresh_token) {
throw new BadRequestError({
- message: "Stripe did not return an account ID for the installed app. Reinstall the app and try again."
+ message:
+ "Stripe did not return an account ID and refresh token for the installed app. Reinstall the app and try again."
});
}
- return accountId;
+ return { accountId, refreshToken: data.refresh_token };
};
/**
@@ -89,9 +106,109 @@ const assertCanManageApiKeys = async (accountId: string) => {
};
export const validateStripeConnectionCredentials = async (config: TStripeConnectionConfig) => {
- const accountId = await exchangeStripeOAuthCode(config.credentials.code);
+ const credentials = await exchangeStripeOAuthCode(config.credentials.code);
+
+ await assertCanManageApiKeys(credentials.accountId);
+
+ return credentials;
+};
+
+const getStoredStripeConnection = async (
+ connectionId: string,
+ appConnectionDAL: Pick<TAppConnectionDALFactory, "findById">,
+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">
+) => {
+ const appConnection = await appConnectionDAL.findById(connectionId);
+
+ if (!appConnection) {
+ throw new NotFoundError({ message: `Connection with ID '${connectionId}' not found` });
+ }
+
+ if (appConnection.app !== AppConnection.Stripe) {
+ throw new BadRequestError({ message: `Connection with ID '${connectionId}' is not a Stripe connection` });
+ }
+
+ const credentials = (await decryptAppConnectionCredentials({
+ orgId: appConnection.orgId,
+ projectId: appConnection.projectId,
+ encryptedCredentials: appConnection.encryptedCredentials,
+ kmsService
+ })) as TStripeConnectionCredentials;
+
+ return { appConnection, credentials };
+};
+
+const throwStripeAuthorizationError = (accountId: string, error: AxiosError): never => {
+ if (isStripeRefreshTokenRejected(error)) {
+ throw new BadRequestError({
+ message: `Infisical is no longer authorized on Stripe account '${accountId}': ${getStripeOAuthErrorDescription(error)}. This happens when the Infisical app is uninstalled from the Stripe account. Reinstall the app and reconnect this connection.`
+ });
+ }
+
+ throw new BadRequestError({
+ message: `Infisical could not confirm its access to Stripe account '${accountId}': ${getStripeOAuthErrorDescription(error)}`
+ });
+};
+
+/**
+ * Every call Infisical makes to the Managed API Keys API uses the app's own key, which works on any
+ * account that has the app installed. Stripe revokes a connection's refresh token when the app is
+ * uninstalled and never restores it on a reinstall, so refreshing before each operation is what
+ * stops a connection made before an uninstall from acting on the account again. A cached result
+ * would leave that window open, so this always goes to Stripe.
+ */
+export const assertStripeConnectionAuthorized = async (
+ connectionId: string,
+ appConnectionDAL: Pick<TAppConnectionDALFactory, "findById" | "updateById">,
+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">
+): Promise<void> => {
+ const { appConnection, credentials } = await getStoredStripeConnection(connectionId, appConnectionDAL, kmsService);
+
+ let data: TStripeOAuthTokenResponse;
+
+ try {
+ data = await requestStripeTokens({ grant_type: "refresh_token", refresh_token: credentials.refreshToken });
+ } catch (error) {
+ if (!(error instanceof AxiosError)) throw error;
+
+ // Refresh tokens are single-use, so a refresh that raced another one for the same connection is
+ // rejected too. Retrying with the token the other refresh stored tells that apart from a revoked
+ // install, without trusting the other refresh's result.
+ const { credentials: latest } = await getStoredStripeConnection(connectionId, appConnectionDAL, kmsService);
+
+ if (!isStripeRefreshTokenRejected(error) || latest.refreshToken === credentials.refreshToken) {
+ return throwStripeAuthorizationError(credentials.accountId, error);
+ }
+
+ try {
+ data = await requestStripeTokens({ grant_type: "refresh_token", refresh_token: latest.refreshToken });
+ } catch (retryError) {
+ if (!(retryError instanceof AxiosError)) throw retryError;
+
+ return throwStripeAuthorizationError(credentials.accountId, retryError);
+ }
+ }
+
+ const returnedAccountId = data?.stripe_user_id ?? data?.account_id;
+
+ if (returnedAccountId && returnedAccountId !== credentials.accountId) {
+ throw new BadRequestError({
+ message: `Stripe returned tokens for account '${returnedAccountId}', but this connection is bound to '${credentials.accountId}'. Reconnect the app on the original account.`
+ });
+ }
+
+ if (!data?.refresh_token) {
+ throw new BadRequestError({
+ message: `Stripe did not return a new refresh token for account '${credentials.accountId}'. Reconnect the app and try again.`
+ });
+ }
- await assertCanManageApiKeys(accountId);
+ const encryptedCredentials = await encryptAppConnectionCredentials({
+ credentials: { accountId: credentials.accountId, refreshToken: data.refresh_token },
+ orgId: appConnection.orgId,
+ projectId: appConnection.projectId,
+ kmsService
+ });
- return { accountId };
+ await appConnectionDAL.updateById(appConnection.id, { encryptedCredentials });
};
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 d4f541dc63..97efaa4d01 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
@@ -26,7 +26,11 @@ export const getStripeSecretKey = () => {
return INF_APP_CONNECTION_STRIPE_SECRET_KEY;
};
-/** The Infisical Stripe App acting on a customer's account, named by Stripe-Context. */
+/**
+ * The Infisical Stripe App acting on a customer's account, named by Stripe-Context. This key reaches
+ * every account the app is installed on, so callers must run assertStripeConnectionAuthorized first.
+ * Stripe only serves the Managed API Keys API to the app's own key, not to OAuth access tokens.
+ */
export const getStripeAppRequestConfig = (accountId: string): AxiosRequestConfig => ({
headers: {
Authorization: `Bearer ${getStripeSecretKey()}`,
@@ -59,8 +63,9 @@ 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.
+ * An uninstall is normally caught earlier, by the refresh in assertStripeConnectionAuthorized. One
+ * that lands between that refresh and the call arrives here as a 403, so 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 app key, gets rethrown as itself rather than reworded into
diff --git a/backend/src/services/app-connection/stripe/stripe-connection-schemas.ts b/backend/src/services/app-connection/stripe/stripe-connection-schemas.ts
index ed40026e64..a98e07d180 100644
--- a/backend/src/services/app-connection/stripe/stripe-connection-schemas.ts
+++ b/backend/src/services/app-connection/stripe/stripe-connection-schemas.ts
@@ -15,10 +15,11 @@ export const StripeConnectionOAuthCredentialsSchema = z.object({
code: z.string().trim().min(1, "OAuth code required").max(500)
});
-// Infisical authenticates with its own Stripe key and names the account with Stripe-Context, so the
-// account ID is the only thing worth keeping from the OAuth exchange.
+// The refresh token is how each operation proves the app is still installed, and it is single-use,
+// so every refresh rewrites it. Only the account ID is ever returned to clients.
export const StripeConnectionOAuthOutputCredentialsSchema = z.object({
- accountId: z.string().trim()
+ accountId: z.string().trim(),
+ refreshToken: z.string()
});
const BaseStripeConnectionSchema = BaseAppConnectionSchema.extend({
@@ -38,7 +39,7 @@ export const StripeConnectionSchema = z.intersection(
export const SanitizedStripeConnectionSchema = z.discriminatedUnion("method", [
BaseStripeConnectionSchema.extend({
method: z.literal(StripeConnectionMethod.OAuth),
- credentials: StripeConnectionOAuthOutputCredentialsSchema
+ credentials: StripeConnectionOAuthOutputCredentialsSchema.pick({ accountId: true })
}).describe(JSON.stringify({ title: `${APP_CONNECTION_NAME_MAP[AppConnection.Stripe]} (OAuth)` }))
]);
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
index aa7543cc90..411bc0243b 100644
--- a/backend/src/services/app-connection/stripe/stripe-connection-service.test.ts
+++ b/backend/src/services/app-connection/stripe/stripe-connection-service.test.ts
@@ -1,6 +1,6 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
-const { getMock } = vi.hoisted(() => ({ getMock: vi.fn() }));
+const { getMock, authorizeMock } = vi.hoisted(() => ({ getMock: vi.fn(), authorizeMock: vi.fn() }));
vi.mock("@app/lib/config/env", () => ({
getConfig: () => ({ INF_APP_CONNECTION_STRIPE_SECRET_KEY: "sk_test_app" })
@@ -9,6 +9,9 @@ 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("./stripe-connection-fns", () => ({
+ assertStripeConnectionAuthorized: authorizeMock
+}));
vi.mock("@app/lib/logger", () => ({
logger: { error: vi.fn(), info: vi.fn(), warn: vi.fn(), debug: vi.fn() }
}));
@@ -36,11 +39,16 @@ const keyPage = (id: string, next?: string) => ({
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
+ vi.fn(async () => ({ id: "connection-id", credentials: { accountId: "acct_123" } })) as any,
+ {} as never,
+ {} as never
);
describe("stripeConnectionService.listApiKeys", () => {
- beforeEach(() => getMock.mockReset());
+ beforeEach(() => {
+ getMock.mockReset();
+ authorizeMock.mockReset();
+ });
it("never returns the plaintext secret Stripe includes in every list item", async () => {
getMock.mockResolvedValueOnce(keyPage("mk_1"));
@@ -75,6 +83,27 @@ describe("stripeConnectionService.listApiKeys", () => {
expect(getMock.mock.calls[1][0]).toBe("https://api.stripe.com/v2/iam/api_keys?page=2");
});
+ it("confirms the connection is still authorized before listing with the app key", async () => {
+ getMock.mockResolvedValueOnce(keyPage("mk_1"));
+
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument
+ await makeService().listApiKeys("connection-id", {} as any);
+
+ const { headers } = getMock.mock.calls[0][1] as { headers: Record<string, string> };
+
+ expect(authorizeMock.mock.invocationCallOrder[0]).toBeLessThan(getMock.mock.invocationCallOrder[0]);
+ expect(headers.Authorization).toBe("Bearer sk_test_app");
+ expect(headers["Stripe-Context"]).toBe("acct_123");
+ });
+
+ it("lists nothing once the app was uninstalled", async () => {
+ authorizeMock.mockRejectedValueOnce(new Error("Infisical is no longer authorized"));
+
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument
+ await expect(makeService().listApiKeys("connection-id", {} as any)).rejects.toThrow("no longer authorized");
+ expect(getMock).not.toHaveBeenCalled();
+ });
+
it("never sends the app credential to a next_page_url outside the Stripe API keys endpoint", async () => {
getMock.mockResolvedValueOnce(keyPage("mk_1", "https://evil.example.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
index 504c4cfb73..ac99a747db 100644
--- a/backend/src/services/app-connection/stripe/stripe-connection-service.ts
+++ b/backend/src/services/app-connection/stripe/stripe-connection-service.ts
@@ -1,6 +1,9 @@
import { OrgServiceActor } from "@app/lib/types";
+import { TKmsServiceFactory } from "@app/services/kms/kms-service";
+import { TAppConnectionDALFactory } from "../app-connection-dal";
import { AppConnection } from "../app-connection-enums";
+import { assertStripeConnectionAuthorized } from "./stripe-connection-fns";
import { listStripeApiKeys, throwStripeApiKeyManagementError } from "./stripe-connection-public-client";
import { TStripeConnection } from "./stripe-connection-types";
@@ -18,10 +21,15 @@ export type TStripeApiKeySummary = {
connectPermissions: string[];
};
-export const stripeConnectionService = (getAppConnection: TGetAppConnectionFunc) => {
+export const stripeConnectionService = (
+ getAppConnection: TGetAppConnectionFunc,
+ appConnectionDAL: Pick<TAppConnectionDALFactory, "findById" | "updateById">,
+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">
+) => {
const listApiKeys = async (connectionId: string, actor: OrgServiceActor): Promise<TStripeApiKeySummary[]> => {
const appConnection = await getAppConnection(AppConnection.Stripe, connectionId, actor);
const { accountId } = appConnection.credentials;
+ await assertStripeConnectionAuthorized(appConnection.id, appConnectionDAL, kmsService);
try {
const keys = await listStripeApiKeys(accountId);
diff --git a/backend/src/services/app-connection/stripe/stripe-connection-types.ts b/backend/src/services/app-connection/stripe/stripe-connection-types.ts
index 163409a8cf..eb77b3954c 100644
--- a/backend/src/services/app-connection/stripe/stripe-connection-types.ts
+++ b/backend/src/services/app-connection/stripe/stripe-connection-types.ts
@@ -5,12 +5,15 @@ import { DiscriminativePick } from "@app/lib/types";
import { AppConnection } from "../app-connection-enums";
import {
CreateStripeConnectionSchema,
+ StripeConnectionOAuthOutputCredentialsSchema,
StripeConnectionSchema,
ValidateStripeConnectionCredentialsSchema
} from "./stripe-connection-schemas";
export type TStripeConnection = z.infer<typeof StripeConnectionSchema>;
+export type TStripeConnectionCredentials = z.infer<typeof StripeConnectionOAuthOutputCredentialsSchema>;
+
export type TStripeConnectionInput = z.infer<typeof CreateStripeConnectionSchema> & {
app: AppConnection.Stripe;
};