Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
fix(secret-rotation): serialize Stripe token refreshes and stop echoing OAuth errors
Calvin09951b00b0e6
diff --git a/backend/src/ee/services/secret-rotation-v2/ldap-password/ldap-password-rotation-fns.ts b/backend/src/ee/services/secret-rotation-v2/ldap-password/ldap-password-rotation-fns.tsindex bd0a49e31e..15314e9cf6 100644--- a/backend/src/ee/services/secret-rotation-v2/ldap-password/ldap-password-rotation-fns.ts+++ b/backend/src/ee/services/secret-rotation-v2/ldap-password/ldap-password-rotation-fns.ts@@ -111,7 +111,15 @@ export const ldapPasswordRotationFactory: TRotationFactory<TLdapPasswordRotationWithConnection,TLdapPasswordRotationGeneratedCredentials,TLdapPasswordRotationInput["temporaryParameters"]-> = (secretRotation, appConnectionDAL, kmsService, gatewayV2Service, gatewayPoolService, passwordValidationContext) => {+> = (+ secretRotation,+ appConnectionDAL,+ kmsService,+ gatewayV2Service,+ gatewayPoolService,+ _keyStore,+ passwordValidationContext+) => {const { connection, parameters, secretsMapping, activeIndex } = secretRotation;const { dn, passwordRequirements } = parameters;diff --git a/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-service.ts b/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-service.tsindex e7b7dd5f39..4f917114ef 100644--- a/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-service.ts+++ b/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-service.ts@@ -169,7 +169,7 @@ export type TSecretRotationV2ServiceFactoryDep = {secretTagDAL: Pick<TSecretTagDALFactory, "saveTagsToSecretV2" | "deleteTagsToSecretV2" | "find">;secretQueueService: Pick<TSecretQueueFactory, "syncSecrets" | "removeSecretReminder">;queueService: Pick<TQueueServiceFactory, "queue">;- appConnectionDAL: Pick<TAppConnectionDALFactory, "findById" | "update" | "updateById">;+ appConnectionDAL: Pick<TAppConnectionDALFactory, "findById" | "update" | "updateById" | "transaction">;folderCommitService: Pick<TFolderCommitServiceFactory, "createCommit">;gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;@@ -621,6 +621,7 @@ export const secretRotationV2ServiceFactory = ({kmsService,gatewayV2Service,gatewayPoolService,+ keyStore,passwordValidationContext);@@ -996,6 +997,7 @@ export const secretRotationV2ServiceFactory = ({kmsService,gatewayV2Service,gatewayPoolService,+ keyStore,passwordValidationContext);@@ -1339,6 +1341,7 @@ export const secretRotationV2ServiceFactory = ({kmsService,gatewayV2Service,gatewayPoolService,+ keyStore,passwordValidationContext);@@ -1663,7 +1666,8 @@ export const secretRotationV2ServiceFactory = ({appConnectionDAL,kmsService,gatewayV2Service,- gatewayPoolService+ gatewayPoolService,+ keyStore);if (!rotationFactory.checkActiveCredentials)@@ -2063,6 +2067,7 @@ export const secretRotationV2ServiceFactory = ({kmsService,gatewayV2Service,gatewayPoolService,+ keyStore,passwordValidationContext);diff --git a/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-types.ts b/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-types.tsindex 9c749dee6c..295f94cddd 100644--- a/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-types.ts+++ b/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-types.ts@@ -1,5 +1,6 @@import { AuditLogInfo } from "@app/ee/services/audit-log/audit-log-types";import { TSqlCredentialsRotationGeneratedCredentials } from "@app/ee/services/secret-rotation-v2/shared/sql-credentials/sql-credentials-rotation-types";+import { TKeyStoreFactory } from "@app/keystore/keystore";import { OrderByDirection } from "@app/lib/types";import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";import { TKmsServiceFactory } from "@app/services/kms/kms-service";@@ -533,10 +534,11 @@ export type TRotationFactory<P extends TSecretRotationV2TemporaryParameters = undefined> = (secretRotation: T,- appConnectionDAL: Pick<TAppConnectionDALFactory, "findById" | "update" | "updateById">,+ appConnectionDAL: Pick<TAppConnectionDALFactory, "findById" | "update" | "updateById" | "transaction">,kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">,gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">,+ keyStore: Pick<TKeyStoreFactory, "acquireLock">,passwordValidationContext?: TRotationPasswordValidationContext) => {issueCredentials: TRotationFactoryIssueCredentials<C, P>;diff --git a/backend/src/ee/services/secret-rotation-v2/shared/sql-credentials/sql-credentials-rotation-fns.ts b/backend/src/ee/services/secret-rotation-v2/shared/sql-credentials/sql-credentials-rotation-fns.tsindex 205897acc8..534393d18c 100644--- a/backend/src/ee/services/secret-rotation-v2/shared/sql-credentials/sql-credentials-rotation-fns.ts+++ b/backend/src/ee/services/secret-rotation-v2/shared/sql-credentials/sql-credentials-rotation-fns.ts@@ -70,6 +70,7 @@ export const sqlCredentialsRotationFactory: TRotationFactory<_kmsService,gatewayV2Service,gatewayPoolService,+ _keyStore,passwordValidationContext) => {const {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.tsindex 48e0c59200..713e069419 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@@ -44,13 +44,14 @@ 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 factory hands appConnectionDAL and kmsService to the authorization check, which is mocked, so-// none of these are reached.-const UNUSED_DEPENDENCIES = [{}, {}, {}, {}] as unknown as [+// The factory hands appConnectionDAL, kmsService and keyStore 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],Parameters<typeof stripeApiKeyRotationFactory>[3],- Parameters<typeof stripeApiKeyRotationFactory>[4]+ Parameters<typeof stripeApiKeyRotationFactory>[4],+ Parameters<typeof stripeApiKeyRotationFactory>[5]];// The factory reads these four fields of the rotation row and nothing else, so the rest of the row@@ -176,7 +177,11 @@ describe("stripeApiKeyRotationFactory", () => {const { headers } = postMock.mock.calls[0][2] as { headers: Record<string, string> };- expect(authorizeMock).toHaveBeenCalledWith("connection-id", {}, {});+ expect(authorizeMock).toHaveBeenCalledWith("connection-id", {+ appConnectionDAL: {},+ kmsService: {},+ keyStore: {}+ });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");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.tsindex 13e497e4f1..2e41dd4738 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@@ -32,7 +32,7 @@ const STRIPE_KEY_NAME_MAX_LENGTH = 100;export const stripeApiKeyRotationFactory: TRotationFactory<TStripeApiKeyRotationWithConnection,TStripeApiKeyRotationGeneratedCredentials-> = (secretRotation, appConnectionDAL, kmsService) => {+> = (secretRotation, appConnectionDAL, kmsService, _gatewayV2Service, _gatewayPoolService, keyStore) => {const {connection,parameters: { permissions, connectPermissions },@@ -43,7 +43,8 @@ export const stripeApiKeyRotationFactory: TRotationFactory<// 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);+ const $assertAuthorized = () =>+ assertStripeConnectionAuthorized(connection.id, { appConnectionDAL, kmsService, keyStore });// 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.diff --git a/backend/src/ee/services/secret-rotation-v2/unix-linux-local-account-rotation/unix-linux-local-account-rotation-fns.ts b/backend/src/ee/services/secret-rotation-v2/unix-linux-local-account-rotation/unix-linux-local-account-rotation-fns.tsindex 78c5d02eef..be92be8ff0 100644--- a/backend/src/ee/services/secret-rotation-v2/unix-linux-local-account-rotation/unix-linux-local-account-rotation-fns.ts+++ b/backend/src/ee/services/secret-rotation-v2/unix-linux-local-account-rotation/unix-linux-local-account-rotation-fns.ts@@ -362,7 +362,15 @@ export const unixLinuxLocalAccountRotationFactory: TRotationFactory<TUnixLinuxLocalAccountRotationWithConnection,TUnixLinuxLocalAccountRotationGeneratedCredentials,TUnixLinuxLocalAccountRotationInput["temporaryParameters"]-> = (secretRotation, appConnectionDAL, kmsService, gatewayV2Service, gatewayPoolService, passwordValidationContext) => {+> = (+ secretRotation,+ appConnectionDAL,+ kmsService,+ gatewayV2Service,+ gatewayPoolService,+ _keyStore,+ passwordValidationContext+) => {const { connection, parameters, secretsMapping, activeIndex } = secretRotation;const {username,diff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.tsindex 5b295b7bfe..28dde0476f 100644--- a/backend/src/keystore/keystore.ts+++ b/backend/src/keystore/keystore.ts@@ -68,6 +68,7 @@ export const KeyStorePrefixes = {LdapDirectoryMachines: (connectionId: string, search: string, limit: number) =>`ldap-directory-machines-${connectionId}-${limit}-${search}` as const,SecretRotationLock: (rotationId: string) => `secret-rotation-v2-mutex-${rotationId}` as const,+ StripeConnectionRefreshLock: (connectionId: string) => `stripe-connection-refresh-mutex-${connectionId}` as const,PamAccountRotationLock: (accountId: string) => `pam-account-rotation-mutex-${accountId}` as const,SecretScanningLock: (dataSourceId: string, resourceExternalId: string) =>`secret-scanning-v2-mutex-${dataSourceId}-${resourceExternalId}` as const,diff --git a/backend/src/services/app-connection/app-connection-service.ts b/backend/src/services/app-connection/app-connection-service.tsindex be8bc38597..02f6302a65 100644--- a/backend/src/services/app-connection/app-connection-service.ts+++ b/backend/src/services/app-connection/app-connection-service.ts@@ -219,7 +219,10 @@ export type TAppConnectionServiceFactoryDep = {appConnectionCredentialRotationService: TAppConnectionCredentialRotationServiceFactory;identityUaDAL: Pick<TIdentityUaDALFactory, "findOne">;gitHubAppDAL: Pick<TGitHubAppDALFactory, "findOne" | "upsertConnectionLink">;- keyStore: Pick<TKeyStoreFactory, "setItemWithExpiryNX" | "deleteItem" | "getItem" | "setItemWithExpiry">;+ keyStore: Pick<+ TKeyStoreFactory,+ "setItemWithExpiryNX" | "deleteItem" | "getItem" | "setItemWithExpiry" | "acquireLock"+ >;};export type TAppConnectionServiceFactory = ReturnType<typeof appConnectionServiceFactory>;@@ -1423,7 +1426,7 @@ export const appConnectionServiceFactory = ({bitbucket: bitbucketConnectionService(connectAppConnectionById),checkly: checklyConnectionService(connectAppConnectionById),supabase: supabaseConnectionService(connectAppConnectionById),- stripe: stripeConnectionService(connectAppConnectionById, appConnectionDAL, kmsService),+ stripe: stripeConnectionService(connectAppConnectionById, { appConnectionDAL, kmsService, keyStore }),rundeck: rundeckConnectionService(connectAppConnectionById),digitalOcean: digitalOceanAppPlatformConnectionService(connectAppConnectionById),netlify: netlifyConnectionService(connectAppConnectionById),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.tsindex 8a28667760..01cc296aa9 100644--- a/backend/src/services/app-connection/stripe/stripe-connection-fns.test.ts+++ b/backend/src/services/app-connection/stripe/stripe-connection-fns.test.ts@@ -13,6 +13,9 @@ vi.mock("@app/lib/config/env", () => ({vi.mock("@app/lib/config/request", () => ({request: { post: postMock, get: vi.fn() }}));+vi.mock("@app/lib/logger", () => ({+ logger: { error: vi.fn(), info: vi.fn(), warn: vi.fn(), debug: vi.fn() }+}));vi.mock("@app/services/app-connection/app-connection-fns", () => ({decryptAppConnectionCredentials: decryptMock,encryptAppConnectionCredentials: encryptMock@@ -21,28 +24,61 @@ vi.mock("@app/services/app-connection/app-connection-fns", () => ({// eslint-disable-next-line import/firstimport { AppConnection } from "../app-connection-enums";// eslint-disable-next-line import/first-import { assertStripeConnectionAuthorized } from "./stripe-connection-fns";+import { assertStripeConnectionAuthorized, validateStripeConnectionCredentials } from "./stripe-connection-fns";-const storedCredentials = (overrides: Record<string, unknown> = {}) => ({- accountId: "acct_123",- refreshToken: "rt_old",- ...overrides-});+type TStored = { accountId: string; refreshToken: string };++const TX = { primary: true };++// Stands in for the connection row: decrypt reads it, and encrypt + updateById write it back, so a+// refresh that follows another sees the token that one stored.+let stored: TStored;const appConnectionDAL = {- findById: vi.fn(async () => ({- id: "connection-id",+ findById: vi.fn(async (...args: [string, unknown?]) => ({+ id: args[0],app: AppConnection.Stripe,orgId: "org-id",projectId: null,encryptedCredentials: Buffer.from("")})),- updateById: vi.fn(async () => ({}))+ updateById: vi.fn(async () => ({})),+ transaction: vi.fn(async <T>(fn: (tx: unknown) => Promise<T>) => fn(TX))};+/** A single mutex per resource, which is the contract redlock gives across pods. */+const makeKeyStore = () => {+ let tail = Promise.resolve();+ const release = vi.fn();++ return {+ release,+ acquireLock: vi.fn(async () => {+ let unlock!: () => void;+ const previous = tail;+ tail = new Promise<void>((resolve) => {+ unlock = resolve;+ });+ await previous;+ return {+ release: async () => {+ release();+ unlock();+ return {} as never;+ }+ };+ })+ };+};++let keyStore: ReturnType<typeof makeKeyStore>;+const authorize = () =>- // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument- assertStripeConnectionAuthorized("connection-id", appConnectionDAL as any, {} as any);+ assertStripeConnectionAuthorized("connection-id", {+ appConnectionDAL: appConnectionDAL as never,+ kmsService: {} as never,+ keyStore: keyStore as never+ });const oauthError = (status: number, error: string, description: string) =>new AxiosError("Request failed", "ERR_BAD_REQUEST", undefined, undefined, {@@ -53,8 +89,6 @@ const oauthError = (status: number, error: string, description: string) =>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 }});@@ -63,74 +97,125 @@ const sentRefreshToken = (call: number) => (postMock.mock.calls[call][1] as URLSdescribe("assertStripeConnectionAuthorized", () => {beforeEach(() => {+ stored = { accountId: "acct_123", refreshToken: "rt_1" };+ keyStore = makeKeyStore();postMock.mockReset();decryptMock.mockReset();+ decryptMock.mockImplementation(async () => ({ ...stored }));encryptMock.mockClear();+ encryptMock.mockImplementation(async ({ credentials }: { credentials: unknown }) => {+ stored = credentials as TStored;+ return { encrypted: credentials };+ });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"));+ it("refreshes on every call with the app key as a bearer token and stores only the new refresh token", async () => {+ postMock.mockResolvedValueOnce(refreshed("rt_2")).mockResolvedValueOnce(refreshed("rt_3"));await authorize();await authorize();- expect(postMock).toHaveBeenCalledTimes(2);+ const config = postMock.mock.calls[0][2] as { headers: Record<string, string>; auth?: unknown };++ expect(config.headers.Authorization).toBe("Bearer sk_test_app");+ expect(config.auth).toBeUndefined();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());+ expect([sentRefreshToken(0), sentRefreshToken(1)]).toEqual(["rt_1", "rt_2"]);+ expect(stored).toEqual({ accountId: "acct_123", refreshToken: "rt_3" });});- 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"));+ it("reads the stored token from the primary, not a replica that may hold a spent one", async () => {+ postMock.mockResolvedValue(refreshed("rt_2"));await authorize();- expect(sentRefreshToken(1)).toBe("rt_raced");- expect(encryptMock.mock.calls[0][0].credentials).toEqual({ accountId: "acct_123", refreshToken: "rt_after_race" });+ expect(appConnectionDAL.findById).toHaveBeenCalledWith("connection-id", TX);});- 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("runs concurrent refreshes one at a time, so the second presents the token the first stored", async () => {+ let finishFirst!: () => void;+ postMock+ .mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ finishFirst = () => resolve(refreshed("rt_2"));+ })+ )+ .mockResolvedValueOnce(refreshed("rt_3"));++ const first = authorize();+ const second = authorize();++ await vi.waitFor(() => expect(postMock).toHaveBeenCalledTimes(1));+ finishFirst();+ await Promise.all([first, second]);++ expect([sentRefreshToken(0), sentRefreshToken(1)]).toEqual(["rt_1", "rt_2"]);+ expect(stored.refreshToken).toBe("rt_3");});- it("asks for a reinstall when the refresh token was revoked", async () => {- decryptMock.mockResolvedValue(storedCredentials());- postMock.mockRejectedValue(invalidGrant());+ it("asks for a reinstall when the refresh token was revoked, without echoing Stripe's description", async () => {+ postMock.mockRejectedValue(oauthError(400, "invalid_grant", "Refresh token does not exist: rt_1"));- 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/+ const error = (await authorize().catch((e: Error) => e)) as Error;++ expect(error.message).toBe(+ "Infisical is no longer authorized on Stripe account 'acct_123'. This happens when the Infisical app is uninstalled from the Stripe account. Reinstall the app and reconnect this connection.");- expect(postMock).toHaveBeenCalledTimes(1);+ expect(error.message).not.toContain("rt_1");+ expect(appConnectionDAL.updateById).not.toHaveBeenCalled();+ expect(keyStore.release).toHaveBeenCalledTimes(1);});it("does not blame an uninstall for a Stripe outage", async () => {- decryptMock.mockResolvedValue(storedCredentials());- postMock.mockRejectedValue(oauthError(503, "api_error", "Service unavailable"));+ postMock.mockRejectedValue(oauthError(503, "api_error", "Service unavailable for rt_1"));await expect(authorize()).rejects.toThrow(- "Infisical could not confirm its access to Stripe account 'acct_123': Service unavailable"+ "Infisical could not confirm its access to Stripe account 'acct_123' (status 503). Try again shortly.");- expect(postMock).toHaveBeenCalledTimes(1);+ });++ it("says the connection is busy when the refresh lock cannot be acquired", async () => {+ keyStore.acquireLock.mockRejectedValueOnce(new Error("lock timeout"));++ await expect(authorize()).rejects.toThrow("Another operation on this Stripe connection is still in progress");+ expect(postMock).not.toHaveBeenCalled();});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();});++ it("names the stranded connection when the refreshed token cannot be saved", async () => {+ postMock.mockResolvedValue(refreshed("rt_2"));+ appConnectionDAL.updateById.mockRejectedValueOnce(new Error("connection terminated"));++ await expect(authorize()).rejects.toThrow(+ "Infisical refreshed its access to Stripe account 'acct_123' but could not save it. Reinstall the app and reconnect this connection."+ );+ });+});++describe("validateStripeConnectionCredentials", () => {+ beforeEach(() => {+ postMock.mockReset();+ });++ it("does not echo the rejected authorization code back to the user", async () => {+ postMock.mockRejectedValue(oauthError(400, "invalid_grant", "Authorization code does not exist: ac_secret"));++ const error = (await validateStripeConnectionCredentials({+ credentials: { code: "ac_secret" }+ } as never).catch((e: Error) => e)) as Error;++ expect(error.message).toBe(+ "The Stripe authorization expired or was already used. Install the app from Stripe again to reconnect."+ );+ expect(error.message).not.toContain("ac_secret");+ });});diff --git a/backend/src/services/app-connection/stripe/stripe-connection-fns.ts b/backend/src/services/app-connection/stripe/stripe-connection-fns.tsindex d9fe003af1..37e35e6c3b 100644--- a/backend/src/services/app-connection/stripe/stripe-connection-fns.ts+++ b/backend/src/services/app-connection/stripe/stripe-connection-fns.ts@@ -1,8 +1,10 @@import { AxiosError } from "axios";+import { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";import { getConfig } from "@app/lib/config/env";import { request } from "@app/lib/config/request";import { BadRequestError, NotFoundError } from "@app/lib/errors";+import { logger } from "@app/lib/logger";import { AppConnection } from "@app/services/app-connection/app-connection-enums";import {decryptAppConnectionCredentials,@@ -21,6 +23,12 @@ import {} from "./stripe-connection-public-client";import { TStripeConnectionConfig, TStripeConnectionCredentials } from "./stripe-connection-types";+type TStripeOAuthErrorResponse = {+ error?: string;+ // Never surfaced or logged: OAuth error descriptions can echo the code or token they rejected.+ error_description?: string;+};+type TStripeOAuthTokenResponse = {refresh_token?: string;// The initial exchange names the account stripe_user_id; the refresh grant names it account_id.@@ -43,24 +51,36 @@ export const getStripeConnectionListItem = () => {};};+// Long enough to cover a slow token call, which is the only thing done while holding it.+const REFRESH_LOCK_DURATION_MS = 30 * 1000;++// Another refresh for the same connection holds the lock for one token call, so waiting up to about+// fifteen seconds rides out a queue of several without turning a stuck lock into a hung rotation.+const REFRESH_LOCK_SETTINGS = { retryCount: 60, retryDelay: 250, retryJitter: 100 };++export type TStripeConnectionAuthorizationDeps = {+ appConnectionDAL: Pick<TAppConnectionDALFactory, "findById" | "updateById" | "transaction">;+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;+ keyStore: Pick<TKeyStoreFactory, "acquireLock">;+};+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" }+ headers: {+ Authorization: `Bearer ${getStripeSecretKey()}`,+ "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";+const getStripeOAuthErrorCode = (error: AxiosError) =>+ (error.response?.data as TStripeOAuthErrorResponse | undefined)?.error;/*** The exchange is also the only proof that the installer controls the account they are claiming: a@@ -72,13 +92,20 @@ const exchangeStripeOAuthCode = async (code: string): Promise<TStripeConnectionCtry {data = await requestStripeTokens({ grant_type: "authorization_code", code });} catch (error) {- if (error instanceof AxiosError) {- throw new BadRequestError({- message: `Stripe rejected the app installation: ${getStripeOAuthErrorDescription(error)}`- });- }+ if (!(error instanceof AxiosError)) throw error;- throw error;+ const errorCode = getStripeOAuthErrorCode(error);++ logger.warn(+ `exchangeStripeOAuthCode: Stripe rejected the authorization code [status=${error.response?.status}] [error=${errorCode}]`+ );++ throw new BadRequestError({+ message:+ errorCode === "invalid_grant"+ ? "The Stripe authorization expired or was already used. Install the app from Stripe again to reconnect."+ : `Stripe rejected the app installation (status ${error.response?.status ?? "unknown"}). Install the app from Stripe again to reconnect.`+ });}const accountId = data?.stripe_user_id ?? data?.account_id;@@ -113,12 +140,15 @@ export const validateStripeConnectionCredentials = async (config: TStripeConnectreturn credentials;};+/**+ * Read from the primary, since the connection's last refresh may have written the token a moment ago+ * and a replica that has not caught up would hand back one Stripe has already spent.+ */const getStoredStripeConnection = async (connectionId: string,- appConnectionDAL: Pick<TAppConnectionDALFactory, "findById">,- kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">+ { appConnectionDAL, kmsService }: Pick<TStripeConnectionAuthorizationDeps, "appConnectionDAL" | "kmsService">) => {- const appConnection = await appConnectionDAL.findById(connectionId);+ const appConnection = await appConnectionDAL.transaction((tx) => appConnectionDAL.findById(connectionId, tx));if (!appConnection) {throw new NotFoundError({ message: `Connection with ID '${connectionId}' not found` });@@ -138,31 +168,9 @@ const getStoredStripeConnection = async (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);+const refreshStripeConnection = async (connectionId: string, deps: TStripeConnectionAuthorizationDeps) => {+ const { appConnection, credentials } = await getStoredStripeConnection(connectionId, deps);+ const { accountId } = credentials;let data: TStripeOAuthTokenResponse;@@ -171,44 +179,93 @@ export const assertStripeConnectionAuthorized = async (} 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);+ const errorCode = getStripeOAuthErrorCode(error);- 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;+ logger.warn(+ `assertStripeConnectionAuthorized: Stripe rejected the token refresh [connectionId=${connectionId}] [accountId=${accountId}] [status=${error.response?.status}] [error=${errorCode}]`+ );- return throwStripeAuthorizationError(credentials.accountId, retryError);- }+ throw new BadRequestError({+ message:+ errorCode === "invalid_grant"+ ? `Infisical is no longer authorized on Stripe account '${accountId}'. This happens when the Infisical app is uninstalled from the Stripe account. Reinstall the app and reconnect this connection.`+ : `Infisical could not confirm its access to Stripe account '${accountId}' (status ${error.response?.status ?? "unknown"}). Try again shortly.`+ });}const returnedAccountId = data?.stripe_user_id ?? data?.account_id;- if (returnedAccountId && returnedAccountId !== credentials.accountId) {+ if (returnedAccountId && returnedAccountId !== 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.`+ message: `Stripe returned tokens for account '${returnedAccountId}', but this connection is bound to '${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.`+ message: `Stripe did not return a new refresh token for account '${accountId}'. Reconnect the app and try again.`});}const encryptedCredentials = await encryptAppConnectionCredentials({- credentials: { accountId: credentials.accountId, refreshToken: data.refresh_token },+ credentials: { accountId, refreshToken: data.refresh_token },orgId: appConnection.orgId,projectId: appConnection.projectId,- kmsService+ kmsService: deps.kmsService});- await appConnectionDAL.updateById(appConnection.id, { encryptedCredentials });+ try {+ await deps.appConnectionDAL.updateById(appConnection.id, { encryptedCredentials });+ } catch (error) {+ // Stripe has already spent the stored token, so the connection cannot recover from this on its own.+ logger.error(+ error,+ `assertStripeConnectionAuthorized: failed to store the refreshed Stripe token [connectionId=${connectionId}] [accountId=${accountId}]`+ );+ throw new BadRequestError({+ message: `Infisical refreshed its access to Stripe account '${accountId}' but could not save it. Reinstall the app and reconnect this connection.`+ });+ }+};++/**+ * 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.+ *+ * Refresh tokens are single-use, so two operations on one connection must not refresh at once: the+ * second would present a token the first just spent. The lock is held only around the token call and+ * the write that stores its result, and is in Redis because a database lock would hold a connection+ * open across the HTTP call.+ */+export const assertStripeConnectionAuthorized = async (+ connectionId: string,+ deps: TStripeConnectionAuthorizationDeps+): Promise<void> => {+ let lock: Awaited<ReturnType<TStripeConnectionAuthorizationDeps["keyStore"]["acquireLock"]>>;++ try {+ lock = await deps.keyStore.acquireLock(+ [KeyStorePrefixes.StripeConnectionRefreshLock(connectionId)],+ REFRESH_LOCK_DURATION_MS,+ REFRESH_LOCK_SETTINGS+ );+ } catch {+ throw new BadRequestError({+ message: "Another operation on this Stripe connection is still in progress. Try again shortly."+ });+ }++ try {+ await refreshStripeConnection(connectionId, deps);+ } finally {+ await lock.release().catch((error) => {+ logger.warn(+ error,+ `assertStripeConnectionAuthorized: failed to release the refresh lock [connectionId=${connectionId}]`+ );+ });+ }};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.tsindex 411bc0243b..84fd97d88a 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@@ -40,7 +40,6 @@ const makeService = () =>stripeConnectionService(// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argumentvi.fn(async () => ({ id: "connection-id", credentials: { accountId: "acct_123" } })) as any,- {} as never,{} as never);diff --git a/backend/src/services/app-connection/stripe/stripe-connection-service.ts b/backend/src/services/app-connection/stripe/stripe-connection-service.tsindex ac99a747db..f65806deb9 100644--- a/backend/src/services/app-connection/stripe/stripe-connection-service.ts+++ b/backend/src/services/app-connection/stripe/stripe-connection-service.ts@@ -1,9 +1,7 @@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 { assertStripeConnectionAuthorized, TStripeConnectionAuthorizationDeps } from "./stripe-connection-fns";import { listStripeApiKeys, throwStripeApiKeyManagementError } from "./stripe-connection-public-client";import { TStripeConnection } from "./stripe-connection-types";@@ -23,13 +21,13 @@ export type TStripeApiKeySummary = {export const stripeConnectionService = (getAppConnection: TGetAppConnectionFunc,- appConnectionDAL: Pick<TAppConnectionDALFactory, "findById" | "updateById">,- kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">+ authorizationDeps: TStripeConnectionAuthorizationDeps) => {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);++ await assertStripeConnectionAuthorized(appConnection.id, authorizationDeps);try {const keys = await listStripeApiKeys(accountId);