-
Notifications
You must be signed in to change notification settings - Fork 3.8k
Expand file tree
/
Copy pathroute.test.ts
More file actions
196 lines (174 loc) · 6.07 KB
/
Copy pathroute.test.ts
File metadata and controls
196 lines (174 loc) · 6.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
/**
* @vitest-environment node
*/
import { createMockRequest, hybridAuthMockFns } from '@sim/testing'
import { beforeEach, describe, expect, it, vi } from 'vitest'
const {
mockExecuteProviderRequest,
mockRequireBillingAttributionHeader,
mockCheckWorkspaceAccess,
mockAuthorizeCredentialUse,
} = vi.hoisted(() => ({
mockExecuteProviderRequest: vi.fn(),
mockRequireBillingAttributionHeader: vi.fn(),
mockCheckWorkspaceAccess: vi.fn(),
mockAuthorizeCredentialUse: vi.fn(),
}))
vi.mock('@/providers', () => ({
executeProviderRequest: mockExecuteProviderRequest,
}))
vi.mock('@/lib/billing/core/billing-attribution', () => ({
BILLING_ATTRIBUTION_HEADER: 'x-sim-billing-attribution',
requireBillingAttributionHeader: mockRequireBillingAttributionHeader,
}))
vi.mock('@/lib/workspaces/permissions/utils', () => ({
checkWorkspaceAccess: mockCheckWorkspaceAccess,
}))
vi.mock('@/lib/auth/credential-access', () => ({
authorizeCredentialUse: mockAuthorizeCredentialUse,
}))
vi.mock('@/app/api/auth/oauth/utils', () => ({
getServiceAccountToken: vi.fn(),
refreshTokenIfNeeded: vi.fn(),
resolveOAuthAccountId: vi.fn(),
}))
vi.mock('@/ee/access-control/utils/permission-check', () => ({
assertPermissionsAllowed: vi.fn(),
IntegrationNotAllowedError: class IntegrationNotAllowedError extends Error {},
ModelNotAllowedError: class ModelNotAllowedError extends Error {},
ProviderNotAllowedError: class ProviderNotAllowedError extends Error {},
}))
import { POST } from '@/app/api/providers/route'
const BILLING_ATTRIBUTION = {
actorUserId: 'user-1',
workspaceId: 'ws-1',
organizationId: 'org-1',
billedAccountUserId: 'owner-1',
billingEntity: { type: 'organization', id: 'org-1' },
billingPeriod: {
start: '2026-07-01T00:00:00.000Z',
end: '2026-08-01T00:00:00.000Z',
},
payerSubscription: null,
}
describe('POST /api/providers', () => {
beforeEach(() => {
vi.clearAllMocks()
hybridAuthMockFns.mockCheckInternalAuth.mockResolvedValue({
success: true,
userId: 'user-1',
authType: 'internal_jwt',
})
mockCheckWorkspaceAccess.mockResolvedValue({ hasAccess: true })
mockRequireBillingAttributionHeader.mockReturnValue(BILLING_ATTRIBUTION)
mockExecuteProviderRequest.mockResolvedValue({
content: 'hello',
model: 'gpt-4o',
tokens: { input: 1, output: 1, total: 2 },
})
})
it('validates the attribution header and forwards it to executeProviderRequest', async () => {
const res = await POST(
createMockRequest(
'POST',
{ provider: 'openai', model: 'gpt-4o', workspaceId: 'ws-1' },
{ 'x-sim-billing-attribution': 'encoded-attribution' }
)
)
expect(res.status).toBe(200)
expect(mockRequireBillingAttributionHeader).toHaveBeenCalledWith(expect.anything(), {
actorUserId: 'user-1',
workspaceId: 'ws-1',
})
expect(mockExecuteProviderRequest).toHaveBeenCalledWith(
'openai',
expect.objectContaining({ billingAttribution: BILLING_ATTRIBUTION })
)
})
it('executes without attribution when the header is absent', async () => {
const res = await POST(
createMockRequest('POST', { provider: 'openai', model: 'gpt-4o', workspaceId: 'ws-1' })
)
expect(res.status).toBe(200)
expect(mockRequireBillingAttributionHeader).not.toHaveBeenCalled()
expect(mockExecuteProviderRequest).toHaveBeenCalledWith(
'openai',
expect.objectContaining({ billingAttribution: undefined })
)
})
it('omits provisional stream output from the execution header', async () => {
mockExecuteProviderRequest.mockResolvedValue({
streamFormat: 'agent-events-v1',
stream: new ReadableStream({
start(controller) {
controller.enqueue({ type: 'text_delta', text: 'hello', turn: 'final' })
controller.close()
},
}),
execution: {
success: true,
output: {
content: '',
model: 'gpt-4o',
tokens: { input: 0, output: 0, total: 0 },
cost: { input: 0, output: 0, total: 0 },
providerTiming: {
startTime: '2026-07-01T00:00:00.000Z',
endTime: '2026-07-01T00:00:00.000Z',
duration: 0,
},
},
logs: [],
metadata: {
startTime: '2026-07-01T00:00:00.000Z',
endTime: '2026-07-01T00:00:00.000Z',
duration: 0,
},
isStreaming: true,
},
})
const res = await POST(
createMockRequest('POST', {
provider: 'openai',
model: 'gpt-4o',
workspaceId: 'ws-1',
stream: true,
})
)
expect(res.status).toBe(200)
expect(await res.text()).toBe('hello')
const executionHeader = JSON.parse(res.headers.get('X-Execution-Data') ?? '{}')
expect(executionHeader.output).toEqual({ model: 'gpt-4o' })
expect(executionHeader.metadata).toEqual({ startTime: '2026-07-01T00:00:00.000Z' })
})
it('rejects an attribution header when the body has no workspaceId to validate against', async () => {
const res = await POST(
createMockRequest(
'POST',
{ provider: 'openai', model: 'gpt-4o' },
{ 'x-sim-billing-attribution': 'encoded-attribution' }
)
)
expect(res.status).toBe(400)
expect(mockRequireBillingAttributionHeader).not.toHaveBeenCalled()
expect(mockExecuteProviderRequest).not.toHaveBeenCalled()
})
it('rejects with 400 when the attribution header does not match the authenticated scope', async () => {
mockRequireBillingAttributionHeader.mockImplementation(() => {
throw new Error('Billing attribution header does not match the authenticated request scope')
})
const res = await POST(
createMockRequest(
'POST',
{ provider: 'openai', model: 'gpt-4o', workspaceId: 'ws-1' },
{ 'x-sim-billing-attribution': 'encoded-attribution' }
)
)
expect(res.status).toBe(400)
const body = await res.json()
expect(body.error).toBe(
'Billing attribution header does not match the authenticated request scope'
)
expect(mockExecuteProviderRequest).not.toHaveBeenCalled()
})
})