Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 1 addition & 4 deletions apps/sim/app/api/billing/update-cost/route.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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()
})
Expand Down
2 changes: 1 addition & 1 deletion apps/sim/app/api/billing/update-cost/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,7 @@ async function updateCostInner(req: NextRequest, span: Span): Promise<NextRespon
return NextResponse.json(
{
success: false,
error: authResult.error || 'Authentication failed',
error: 'Unauthorized',
},
{ status: 401 }
)
Expand Down
7 changes: 4 additions & 3 deletions apps/sim/lib/auth/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ import { isSsoCallbackPath, resolveSsoCallbackProviderId } from '@/lib/auth/sso/
import { configuredSsoPlugin } from '@/lib/auth/sso/plugin'
import {
assertPersonalCheckoutAllowed,
assertSelfServeCheckoutPlan,
assertSelfServeCheckoutRequest,
authorizeSubscriptionReference,
isPersonalCheckoutRequest,
} from '@/lib/billing/authorization'
Expand Down Expand Up @@ -1213,7 +1213,7 @@ export const auth = betterAuth({
const sessionUserId = session?.user?.id
if (sessionUserId) {
const requestBody = ctx.body ?? {}
assertSelfServeCheckoutPlan(requestBody.plan)
assertSelfServeCheckoutRequest(requestBody)
const referenceId = resolveCheckoutReferenceId(
requestBody,
sessionUserId,
Expand Down Expand Up @@ -1607,7 +1607,8 @@ export const auth = betterAuth({
},
subscription: {
enabled: true,
plans: getPlans(),
// Enterprise is issued by the team, never checked out, so the plugin never offers it.
plans: getPlans().filter((plan) => !isEnterprise(plan.name)),
authorizeReference: async ({ user, referenceId, action }, ctx) => {
const body: unknown = ctx?.body
const requestedPlan =
Expand Down
44 changes: 34 additions & 10 deletions apps/sim/lib/billing/authorization.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ vi.mock('@/lib/billing/enterprise-outbox', () => {

import {
assertPersonalCheckoutAllowed,
assertSelfServeCheckoutPlan,
assertSelfServeCheckoutRequest,
authorizeSubscriptionReference,
isPersonalCheckoutRequest,
} from '@/lib/billing/authorization'
Expand Down Expand Up @@ -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 () => {
Expand All @@ -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 () => {
Expand All @@ -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 () => {
Expand All @@ -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)

Expand All @@ -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()
})
})

Expand Down
60 changes: 48 additions & 12 deletions apps/sim/lib/billing/authorization.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,17 +74,48 @@ async function assertNotBilledThroughMarketplace(referenceId: string): Promise<v
})
}

/** A checkout's plan name as the Stripe plugin matches it: trimmed and case-insensitive. */
function normalizeCheckoutPlan(plan: unknown): string | undefined {
return typeof plan === 'string' ? plan.trim().toLowerCase() : undefined
}

/** The most seats one self-serve checkout may request. */
const MAX_CHECKOUT_SEATS = 1000

/**
* Refuse a self-serve checkout for the Enterprise plan. Enterprise is issued by the Sim team with
* its own Stripe price and metadata, so the Stripe plugin's placeholder price can never check out,
* and its write to a pending subscription row fails the Enterprise metadata constraint.
* Refuse what a self-serve checkout may not carry. Enterprise is issued by the Sim team with its
* own Stripe price and terms, so it is never a checkout plan. Subscription metadata is Sim's own:
* the Stripe plugin copies a request's `metadata` onto the Stripe subscription, where billing
* reads plan terms, and Sim's client never sends any. Seats must be a whole number in range.
*/
export function assertSelfServeCheckoutPlan(plan: unknown): void {
if (typeof plan !== 'string' || !isEnterprise(plan)) return
logger.warn('Blocking checkout - Enterprise is not a self-serve plan')
throw new APIError('BAD_REQUEST', {
message: 'Enterprise plans are set up by our team. Contact sales to get started.',
})
export function assertSelfServeCheckoutRequest(body: {
plan?: unknown
metadata?: unknown
seats?: unknown
}): void {
if (isEnterprise(normalizeCheckoutPlan(body.plan))) {
logger.warn('Blocking checkout - Enterprise is not a self-serve plan')
throw new APIError('BAD_REQUEST', {
message: 'Enterprise plans are set up by our team. Contact sales to get started.',
})
}
if (body.metadata !== undefined) {
logger.warn('Blocking checkout - request carries subscription metadata')
throw new APIError('BAD_REQUEST', { message: 'Checkout does not accept metadata.' })
}
if (
body.seats !== undefined &&
!(
typeof body.seats === 'number' &&
Number.isInteger(body.seats) &&
body.seats >= 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. */
Expand Down Expand Up @@ -146,7 +177,7 @@ export function isPersonalCheckoutRequest(
export async function assertPersonalCheckoutAllowed(userId: string, plan?: unknown): Promise<void> {
await assertNotBilledThroughMarketplace(userId)
await assertNoBoundIncompleteSubscription(userId)
if (typeof plan === 'string' && isOrgPlan(plan)) {
if (isOrgPlan(normalizeCheckoutPlan(plan))) {
await assertNoPersonalTrial(userId)
}

Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -252,5 +288,5 @@ export async function authorizeSubscriptionReference(
}
}

return isOrganizationOwnerOrAdmin(userId, referenceId)
return true
}
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Comment thread
waleedlatif1 marked this conversation as resolved.
Resolved
*
* 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
Expand Down Expand Up @@ -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' },
])
})
})
10 changes: 10 additions & 0 deletions apps/sim/lib/billing/webhooks/enterprise.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
7 changes: 6 additions & 1 deletion apps/sim/lib/workflows/executor/execute-workflow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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,
Expand Down
13 changes: 8 additions & 5 deletions apps/sim/providers/index.ts
Original file line number Diff line number Diff line change
@@ -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'
Expand Down Expand Up @@ -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
}
}
Expand Down
Loading