-
Notifications
You must be signed in to change notification settings - Fork 13.5k
fix: handle Stripe API errors in OAuth account connection flow #29247
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
calebcgates
wants to merge
3
commits into
calcom:main
from
calebcgates:fix/stripe-oauth-error-handling
Closed
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,194 @@ | ||
| import { BadRequestException, InternalServerErrorException, UnauthorizedException } from "@nestjs/common"; | ||
| import { ConfigService } from "@nestjs/config"; | ||
| import { Test, TestingModule } from "@nestjs/testing"; | ||
| import Stripe from "stripe"; | ||
|
|
||
| import { OAuthCallbackState, StripeService } from "./stripe.service"; | ||
|
|
||
| const mockOAuthToken = jest.fn(); | ||
| const mockAccountsRetrieve = jest.fn(); | ||
|
|
||
| const mockFindAllCredentialsByTypeAndUserId = jest.fn().mockResolvedValue([]); | ||
| const mockDeleteAppCredentials = jest.fn(); | ||
| const mockCreateAppCredential = jest.fn(); | ||
|
|
||
| jest.mock("@/modules/credentials/credentials.repository", () => { | ||
| return { | ||
| CredentialsRepository: jest.fn().mockImplementation(() => ({ | ||
| findAllCredentialsByTypeAndUserId: mockFindAllCredentialsByTypeAndUserId, | ||
| findCredentialByTypeAndUserId: jest.fn(), | ||
| })), | ||
| }; | ||
| }); | ||
|
|
||
| jest.mock("@/modules/users/users.repository", () => { | ||
| return { | ||
| UsersRepository: jest.fn().mockImplementation(() => ({})), | ||
| UserWithProfile: {}, | ||
| }; | ||
| }); | ||
|
|
||
| jest.mock("@/modules/memberships/memberships.repository", () => { | ||
| return { | ||
| MembershipsRepository: jest.fn().mockImplementation(() => ({})), | ||
| }; | ||
| }); | ||
|
|
||
| jest.mock("@/modules/apps/apps.repository", () => { | ||
| return { | ||
| AppsRepository: jest.fn().mockImplementation(() => ({ | ||
| getAppBySlug: jest.fn(), | ||
| deleteAppCredentials: mockDeleteAppCredentials, | ||
| createAppCredential: mockCreateAppCredential, | ||
| })), | ||
| }; | ||
| }); | ||
|
|
||
| jest.mock("@/modules/stripe/utils/newStripeInstance", () => ({ | ||
| stripeInstance: { | ||
| oauth: { token: (...args: unknown[]) => mockOAuthToken(...args) }, | ||
| accounts: { retrieve: (...args: unknown[]) => mockAccountsRetrieve(...args) }, | ||
| }, | ||
| })); | ||
|
|
||
| // eslint-disable-next-line @typescript-eslint/no-var-requires | ||
| const { CredentialsRepository } = require("@/modules/credentials/credentials.repository"); | ||
| // eslint-disable-next-line @typescript-eslint/no-var-requires | ||
| const { AppsRepository } = require("@/modules/apps/apps.repository"); | ||
| // eslint-disable-next-line @typescript-eslint/no-var-requires | ||
| const { MembershipsRepository } = require("@/modules/memberships/memberships.repository"); | ||
| // eslint-disable-next-line @typescript-eslint/no-var-requires | ||
| const { UsersRepository } = require("@/modules/users/users.repository"); | ||
|
|
||
| describe("StripeService", () => { | ||
| let service: StripeService; | ||
|
|
||
| const mockState: OAuthCallbackState = { | ||
| accessToken: "test-token", | ||
| returnTo: "/settings", | ||
| }; | ||
|
|
||
| const mockConfigGet = jest.fn((key: string) => { | ||
| const config: Record<string, string> = { | ||
| "stripe.apiKey": "sk_test_fake", | ||
| "api.url": "https://api.test.com", | ||
| "app.baseUrl": "https://app.test.com", | ||
| "env.type": "test", | ||
| "stripe.teamMonthlyPriceId": "price_test", | ||
| }; | ||
| return config[key] ?? ""; | ||
| }); | ||
|
|
||
| beforeEach(async () => { | ||
| const module: TestingModule = await Test.createTestingModule({ | ||
| providers: [ | ||
| StripeService, | ||
| { provide: ConfigService, useValue: { get: mockConfigGet } }, | ||
| { provide: AppsRepository, useValue: { getAppBySlug: jest.fn(), deleteAppCredentials: mockDeleteAppCredentials, createAppCredential: mockCreateAppCredential } }, | ||
| { provide: CredentialsRepository, useValue: { findAllCredentialsByTypeAndUserId: mockFindAllCredentialsByTypeAndUserId } }, | ||
| { provide: MembershipsRepository, useValue: {} }, | ||
| { provide: UsersRepository, useValue: {} }, | ||
| ], | ||
| }).compile(); | ||
|
|
||
| service = module.get<StripeService>(StripeService); | ||
|
|
||
| jest.clearAllMocks(); | ||
| mockFindAllCredentialsByTypeAndUserId.mockResolvedValue([]); | ||
| }); | ||
|
|
||
| describe("saveStripeAccount", () => { | ||
| it("throws UnauthorizedException when userId is falsy", async () => { | ||
| await expect(service.saveStripeAccount(mockState, "code_123", 0)).rejects.toThrow(UnauthorizedException); | ||
| }); | ||
|
|
||
| it("succeeds with valid OAuth code and no stripe_user_id", async () => { | ||
| mockOAuthToken.mockResolvedValue({ access_token: "tok_123" }); | ||
|
|
||
| const result = await service.saveStripeAccount(mockState, "code_123", 1); | ||
|
|
||
| expect(mockOAuthToken).toHaveBeenCalledWith({ | ||
| grant_type: "authorization_code", | ||
| code: "code_123", | ||
| }); | ||
| expect(result).toEqual({ url: "/settings" }); | ||
| }); | ||
|
|
||
| it("retrieves account details when stripe_user_id is present", async () => { | ||
| mockOAuthToken.mockResolvedValue({ access_token: "tok_123", stripe_user_id: "acct_123" }); | ||
| mockAccountsRetrieve.mockResolvedValue({ default_currency: "usd" }); | ||
|
|
||
| const result = await service.saveStripeAccount(mockState, "code_123", 1); | ||
|
|
||
| expect(mockAccountsRetrieve).toHaveBeenCalledWith("acct_123"); | ||
| expect(result).toEqual({ url: "/settings" }); | ||
| }); | ||
|
|
||
| it("throws BadRequestException on StripeInvalidGrantError (expired/invalid code)", async () => { | ||
| mockOAuthToken.mockRejectedValue( | ||
| new Stripe.errors.StripeInvalidGrantError({ | ||
| message: "Authorization code has been revoked", | ||
| type: "invalid_grant", | ||
| }) | ||
| ); | ||
|
|
||
| await expect(service.saveStripeAccount(mockState, "expired_code", 1)).rejects.toThrow(BadRequestException); | ||
| await expect(service.saveStripeAccount(mockState, "expired_code", 1)).rejects.toThrow( | ||
| "Invalid or expired Stripe authorization code" | ||
| ); | ||
| }); | ||
|
|
||
| it("throws InternalServerErrorException on unexpected Stripe OAuth error", async () => { | ||
| mockOAuthToken.mockRejectedValue(new Error("network timeout")); | ||
|
|
||
| await expect(service.saveStripeAccount(mockState, "code_123", 1)).rejects.toThrow( | ||
| InternalServerErrorException | ||
| ); | ||
| await expect(service.saveStripeAccount(mockState, "code_123", 1)).rejects.toThrow( | ||
| "Failed to exchange Stripe authorization code" | ||
| ); | ||
| }); | ||
|
|
||
| it("throws BadRequestException on StripeInvalidRequestError (deleted account)", async () => { | ||
| mockOAuthToken.mockResolvedValue({ access_token: "tok_123", stripe_user_id: "acct_deleted" }); | ||
| mockAccountsRetrieve.mockRejectedValue( | ||
| new Stripe.errors.StripeInvalidRequestError({ | ||
| message: "No such account", | ||
| type: "invalid_request_error", | ||
| }) | ||
| ); | ||
|
|
||
| await expect(service.saveStripeAccount(mockState, "code_123", 1)).rejects.toThrow(BadRequestException); | ||
| await expect(service.saveStripeAccount(mockState, "code_123", 1)).rejects.toThrow( | ||
| "Stripe account could not be found" | ||
| ); | ||
| }); | ||
|
|
||
| it("throws InternalServerErrorException on unexpected Stripe account retrieval error", async () => { | ||
| mockOAuthToken.mockResolvedValue({ access_token: "tok_123", stripe_user_id: "acct_123" }); | ||
| mockAccountsRetrieve.mockRejectedValue(new Error("connection reset")); | ||
|
|
||
| await expect(service.saveStripeAccount(mockState, "code_123", 1)).rejects.toThrow( | ||
| InternalServerErrorException | ||
| ); | ||
| await expect(service.saveStripeAccount(mockState, "code_123", 1)).rejects.toThrow( | ||
| "Failed to retrieve Stripe account details" | ||
| ); | ||
| }); | ||
|
|
||
| it("deletes existing credentials before creating new ones", async () => { | ||
| mockOAuthToken.mockResolvedValue({ access_token: "tok_123" }); | ||
| mockFindAllCredentialsByTypeAndUserId.mockResolvedValue([{ id: 10 }, { id: 20 }]); | ||
|
|
||
| await service.saveStripeAccount(mockState, "code_123", 1); | ||
|
|
||
| expect(mockDeleteAppCredentials).toHaveBeenCalledWith([10, 20], 1); | ||
| expect(mockCreateAppCredential).toHaveBeenCalledWith( | ||
| "stripe_payment", | ||
| expect.any(Object), | ||
| 1, | ||
| "stripe" | ||
| ); | ||
| }); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Add an early guard for missing OAuth
codebefore calling Stripe.Line [109] allows an empty/undefined
codeto reachoauth.token, which then falls into the 500 path. This should fail fast as a client error (400) before the external call.Suggested fix
async saveStripeAccount(state: OAuthCallbackState, code: string, userId: number): Promise<{ url: string }> { if (!userId) { throw new UnauthorizedException("Invalid Access token."); } + if (!code?.trim()) { + throw new BadRequestException("Missing Stripe authorization code."); + } let response; try { response = await stripeInstance.oauth.token({ grant_type: "authorization_code", - code: code?.toString(), + code, });🤖 Prompt for AI Agents