diff --git a/apps/sim/app/api/billing/update-cost/route.test.ts b/apps/sim/app/api/billing/update-cost/route.test.ts index 2a2ee681ae4..7791174c0a2 100644 --- a/apps/sim/app/api/billing/update-cost/route.test.ts +++ b/apps/sim/app/api/billing/update-cost/route.test.ts @@ -222,10 +222,7 @@ describe('POST /api/billing/update-cost — workspaceId attribution', () => { ) expect(res.status).toBe(401) - await expect(res.json()).resolves.toEqual({ - success: false, - error: 'Invalid internal API key', - }) + await expect(res.json()).resolves.toEqual({ success: false, error: 'Unauthorized' }) expect(mockCheckInternalApiKey).toHaveBeenCalledTimes(1) expect(mockRecordCumulativeUsage).not.toHaveBeenCalled() }) diff --git a/apps/sim/app/api/billing/update-cost/route.ts b/apps/sim/app/api/billing/update-cost/route.ts index 27f1f545485..b1b60909c8f 100644 --- a/apps/sim/app/api/billing/update-cost/route.ts +++ b/apps/sim/app/api/billing/update-cost/route.ts @@ -207,7 +207,7 @@ async function updateCostInner(req: NextRequest, span: Span): Promise !isEnterprise(plan.name)), authorizeReference: async ({ user, referenceId, action }, ctx) => { const body: unknown = ctx?.body const requestedPlan = diff --git a/apps/sim/lib/billing/authorization.test.ts b/apps/sim/lib/billing/authorization.test.ts index de98327b61d..a75c93d422f 100644 --- a/apps/sim/lib/billing/authorization.test.ts +++ b/apps/sim/lib/billing/authorization.test.ts @@ -32,7 +32,7 @@ vi.mock('@/lib/billing/enterprise-outbox', () => { import { assertPersonalCheckoutAllowed, - assertSelfServeCheckoutPlan, + assertSelfServeCheckoutRequest, authorizeSubscriptionReference, isPersonalCheckoutRequest, } from '@/lib/billing/authorization' @@ -75,7 +75,6 @@ describe('authorizeSubscriptionReference', () => { ).rejects.toThrow(/Enterprise plan setup in progress/) expect(mockAssertNoUnresolved).toHaveBeenCalledWith(expect.anything(), 'org-1') - expect(mockIsOwnerOrAdmin).not.toHaveBeenCalled() }) it('blocks an organization checkout while its bound Stripe subscription is incomplete', async () => { @@ -89,7 +88,6 @@ describe('authorizeSubscriptionReference', () => { expect(mockHasPaidSubscription).not.toHaveBeenCalled() expect(mockAssertNoUnresolved).not.toHaveBeenCalled() - expect(mockIsOwnerOrAdmin).not.toHaveBeenCalled() }) it('rejects an organization checkout for a pro plan — org references only hold Team/Enterprise', async () => { @@ -98,7 +96,6 @@ describe('authorizeSubscriptionReference', () => { ).rejects.toThrow('Organizations can only subscribe to Team or Enterprise plans.') expect(mockHasPaidSubscription).not.toHaveBeenCalled() - expect(mockIsOwnerOrAdmin).not.toHaveBeenCalled() }) it('rejects an organization checkout when the plan cannot be determined (fail closed)', async () => { @@ -107,6 +104,18 @@ describe('authorizeSubscriptionReference', () => { ).rejects.toThrow('Organizations can only subscribe to Team or Enterprise plans.') }) + it("refuses a non-member without revealing the organization's billing state", async () => { + mockIsOwnerOrAdmin.mockResolvedValueOnce(false) + mockHasPaidSubscription.mockResolvedValueOnce(true) + + await expect( + authorizeSubscriptionReference('outsider-1', 'org-1', 'upgrade-subscription', 'team_6000') + ).resolves.toBe(false) + + expect(mockHasPaidSubscription).not.toHaveBeenCalled() + expect(mockAssertNoUnresolved).not.toHaveBeenCalled() + }) + it('blocks an organization checkout when the organization already has an active subscription', async () => { mockHasPaidSubscription.mockResolvedValueOnce(true) @@ -116,16 +125,31 @@ describe('authorizeSubscriptionReference', () => { }) }) -describe('assertSelfServeCheckoutPlan', () => { - it('refuses a self-serve Enterprise checkout with a client error', () => { - expect(() => assertSelfServeCheckoutPlan('enterprise')).toThrow( +describe('assertSelfServeCheckoutRequest', () => { + it.each(['enterprise', 'Enterprise', ' ENTERPRISE '])( + 'refuses a self-serve Enterprise checkout named %j with a client error', + (plan) => { + expect(() => assertSelfServeCheckoutRequest({ plan })).toThrow( + expect.objectContaining({ statusCode: 400 }) + ) + } + ) + + it('refuses a checkout that carries subscription metadata', () => { + expect(() => + assertSelfServeCheckoutRequest({ plan: 'team_6000', metadata: { plan: 'enterprise' } }) + ).toThrow(expect.objectContaining({ statusCode: 400 })) + }) + + it.each([0, -3, 2.5, 100_000, '5'])('refuses %j seats', (seats) => { + expect(() => assertSelfServeCheckoutRequest({ plan: 'team_6000', seats })).toThrow( expect.objectContaining({ statusCode: 400 }) ) }) - it('admits self-serve Pro and Team checkouts', () => { - expect(() => assertSelfServeCheckoutPlan('pro_6000')).not.toThrow() - expect(() => assertSelfServeCheckoutPlan('team_25000')).not.toThrow() + it('admits a Pro checkout and a Team checkout for whole seats', () => { + expect(() => assertSelfServeCheckoutRequest({ plan: 'pro_6000' })).not.toThrow() + expect(() => assertSelfServeCheckoutRequest({ plan: 'team_25000', seats: 12 })).not.toThrow() }) }) diff --git a/apps/sim/lib/billing/authorization.ts b/apps/sim/lib/billing/authorization.ts index 472a453a099..013280687a4 100644 --- a/apps/sim/lib/billing/authorization.ts +++ b/apps/sim/lib/billing/authorization.ts @@ -74,17 +74,48 @@ async function assertNotBilledThroughMarketplace(referenceId: string): Promise= 1 && + body.seats <= MAX_CHECKOUT_SEATS + ) + ) { + throw new APIError('BAD_REQUEST', { + message: `Seats must be a whole number from 1 to ${MAX_CHECKOUT_SEATS}.`, + }) + } } /** Refuse an organization-plan upgrade while the account's own Pro plan is still in its free trial. */ @@ -146,7 +177,7 @@ export function isPersonalCheckoutRequest( export async function assertPersonalCheckoutAllowed(userId: string, plan?: unknown): Promise { await assertNotBilledThroughMarketplace(userId) await assertNoBoundIncompleteSubscription(userId) - if (typeof plan === 'string' && isOrgPlan(plan)) { + if (isOrgPlan(normalizeCheckoutPlan(plan))) { await assertNoPersonalTrial(userId) } @@ -203,11 +234,16 @@ export async function authorizeSubscriptionReference( return true } + // Membership first, so the organization's billing state is never revealed to an outsider. + if (!(await isOrganizationOwnerOrAdmin(userId, referenceId))) { + return false + } + if (action === 'upgrade-subscription') { await assertNotBilledThroughMarketplace(referenceId) } - if (action === 'upgrade-subscription' && !isOrgPlan(plan)) { + if (action === 'upgrade-subscription' && !isOrgPlan(normalizeCheckoutPlan(plan))) { logger.warn('Blocking checkout - organizations can only subscribe to Team or Enterprise', { userId, referenceId, @@ -252,5 +288,5 @@ export async function authorizeSubscriptionReference( } } - return isOrganizationOwnerOrAdmin(userId, referenceId) + return true } diff --git a/apps/sim/lib/billing/webhooks/enterprise-missing-organization.integration.ts b/apps/sim/lib/billing/webhooks/enterprise-missing-organization.integration.ts index ea72f5e8559..5d50c4d227f 100644 --- a/apps/sim/lib/billing/webhooks/enterprise-missing-organization.integration.ts +++ b/apps/sim/lib/billing/webhooks/enterprise-missing-organization.integration.ts @@ -11,6 +11,8 @@ * seeds an organization owned by that nonexistent user; * - acknowledging permanent failures swallows a transient one (an issuance whose Stripe writes * have not landed yet), so the event is never redelivered. + * - a self-serve checkout subscription whose metadata claims Enterprise terms is recorded as + * Enterprise. * * The copied tables carry no foreign keys, so an attempted organization creation for a dangling * reference persists here instead of being rolled back by the member foreign key: the suite @@ -369,3 +371,34 @@ describe('Enterprise issuance that Stripe has not caught up with', () => { }) }) }) + +describe('Self-serve checkout subscription that claims Enterprise terms', () => { + it('keeps the subscription on its checked-out plan', async () => { + const organizationId = `org_${generateId()}` + await testDatabase + .insert(organization) + .values({ id: organizationId, name: 'Org', slug: organizationId }) + const rowId = generateId() + // The Stripe plugin stamps its row id on every checkout subscription's metadata. + const customer = await createEnterpriseCustomer(organizationId, { + metadata: { subscriptionId: rowId, usageLimitCredits: String(USAGE_LIMIT_CREDITS) }, + }) + await testDatabase.insert(subscription).values({ + id: rowId, + plan: 'team_6000', + referenceId: organizationId, + status: 'active', + seats: 5, + stripeSubscriptionId: customer.stripeSubscriptionId, + stripeCustomerId: customer.stripeCustomerId, + cancelAtPeriodEnd: false, + }) + + const response = await renew(customer.stripeSubscriptionId) + + expect(response.status).toBe(200) + expect(await subscriptionRowsFor(customer.stripeSubscriptionId)).toEqual([ + { referenceId: organizationId, plan: 'team_6000' }, + ]) + }) +}) diff --git a/apps/sim/lib/billing/webhooks/enterprise.ts b/apps/sim/lib/billing/webhooks/enterprise.ts index abf692bb32b..d9de5a3f056 100644 --- a/apps/sim/lib/billing/webhooks/enterprise.ts +++ b/apps/sim/lib/billing/webhooks/enterprise.ts @@ -135,6 +135,16 @@ async function reconcileManualEnterpriseSubscription( const metadata = stripeSubscription.metadata || {} + // The Stripe plugin stamps its own row id on every self-serve checkout's subscription. Enterprise + // is issued by the team and never checked out, so such a subscription is never Enterprise, + // whatever plan its metadata claims. + if (typeof metadata.subscriptionId === 'string') { + logger.error('[subscription] Refusing Enterprise terms on a self-serve checkout subscription', { + subscriptionId: stripeSubscription.id, + }) + return + } + const referenceId = typeof metadata.referenceId === 'string' && metadata.referenceId.length > 0 ? metadata.referenceId diff --git a/apps/sim/lib/workflows/executor/execute-workflow.ts b/apps/sim/lib/workflows/executor/execute-workflow.ts index 6f66c39675b..a8f29d4cf4a 100644 --- a/apps/sim/lib/workflows/executor/execute-workflow.ts +++ b/apps/sim/lib/workflows/executor/execute-workflow.ts @@ -6,6 +6,7 @@ import { assertBillingAttributionSnapshot, type BillingAttributionSnapshot, } from '@/lib/billing/core/attribution' +import { isHostedKeyPaidPlanFailure } from '@/lib/billing/core/hosted-key-access' import type { AsyncExecutionCorrelation } from '@/lib/core/async-jobs/types' import { LoggingSession } from '@/lib/logs/execution/logging-session' import { captureServerEvent } from '@/lib/posthog/server' @@ -301,7 +302,11 @@ export async function executeWorkflow( attachExecutionResult(error, executionResult) } const errorDiagnostic = loggingSession.projectDiagnosticError(error) - logger.error('Workflow execution failed', errorDiagnostic, { requestId }) + if (isHostedKeyPaidPlanFailure(toError(error).message)) { + logger.info('Workflow execution refused for the payer plan', errorDiagnostic, { requestId }) + } else { + logger.error('Workflow execution failed', errorDiagnostic, { requestId }) + } captureServerEvent( actorUserId, diff --git a/apps/sim/providers/index.ts b/apps/sim/providers/index.ts index b00509bec06..038e5d27f3e 100644 --- a/apps/sim/providers/index.ts +++ b/apps/sim/providers/index.ts @@ -1,6 +1,7 @@ import { createLogger } from '@sim/logger' import { toError } from '@sim/utils/errors' import { getApiKeyWithBYOK } from '@/lib/api-key/byok' +import { HostedKeyRequiresPaidPlanError } from '@/lib/billing/core/hosted-key-access' import { env, envNumber } from '@/lib/core/config/env' import type { ConversationUsageTotal } from '@/lib/memory/conversation-types' import { filterModelSafeWorkspaceFileAttachments } from '@/lib/uploads/contexts/workspace/file-secret-provenance' @@ -274,11 +275,13 @@ export async function executeProviderRequest( isBYOK, }) } catch (error) { - logger.error('Failed to resolve API key:', { - provider: providerId, - model: request.model, - error: toError(error).message, - }) + const details = { provider: providerId, model: request.model, error: toError(error).message } + // A free payer refused Sim's hosted key is an expected outcome, not a fault. + if (error instanceof HostedKeyRequiresPaidPlanError) { + logger.info('Hosted key refused for a free payer', details) + } else { + logger.error('Failed to resolve API key:', details) + } throw error } }