Skip to content

Commit aad4119

Browse files
authored
fix(v2): bound workspace source body reservations per caller and 404 the source routes on the mcp host (#10607)
* fix(v2): bound workspace source body reservations per caller and 404 the source routes on the mcp host A workspace source apply or plan reserves room for its body before the use case authorizes it, from a lane budget every caller shares, so a few slow-trickled bodies from one API key held every tenant's room (429s until the socket timed out). Each caller (the user behind the credential, or a workspace key's workspace) now holds at most a cap's worth of bodies per lane, and a body not read by a deadline that grows with its declared size is answered 408 and frees its room. The proxy matcher leaves these routes out so Next never buffers their bodies, which also skipped the proxy's 404 for the dedicated MCP host. defineV2JsonRoute now answers that host 404 before admitting the caller or reserving room. * fix(v2): fail fast on an unholdable source body caller and declare mcp dispatch body length A source body is held for the workspace a key belongs to or the person behind the credential; a principal with neither now throws instead of sharing one holder per principal kind. The MCP in-process dispatch declares its body's length, so a source plan or apply sent over MCP reserves what it holds rather than a full cap. The read deadline timer is cleared only in finally, and the source route docs name the per-caller 429 and the 408. * fix(v2): declare the actorless gap in the source body holder
1 parent b539715 commit aad4119

11 files changed

Lines changed: 357 additions & 41 deletions

File tree

‎apps/sim/app/api/v2/workspaces/[workspaceId]/source/plan/route.test.ts‎

Lines changed: 101 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,9 @@ import {
44
v2RateLimiterModuleMock,
55
v2RouteMocks,
66
} from '@sim/testing'
7+
import { resetEnvMock, setEnv } from '@sim/testing/mocks/env.mock'
78
import { NextRequest } from 'next/server'
8-
import { beforeEach, describe, expect, it, vi } from 'vitest'
9+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
910

1011
const mocks = vi.hoisted(() => ({ plan: vi.fn() }))
1112

@@ -31,6 +32,37 @@ const auth = {
3132
keyType: 'workspace' as const,
3233
}
3334

35+
/** The next request is sent with a personal key of its own user, a caller apart from `auth`'s. */
36+
function asCaller(userId: string) {
37+
v2RouteMocks.authenticate.mockResolvedValueOnce({
38+
principal: { kind: 'personal_api_key', userId, keyId: `key-${userId}`, access: 'read' },
39+
rateLimitSubjectIds: [`api-key:key-${userId}`, `user:${userId}`],
40+
rateLimitSubscription: null,
41+
keyType: 'personal',
42+
})
43+
}
44+
45+
/** A plan whose body declares no length, so it reserves a body at the cap, and never arrives. */
46+
function stalledPlan(onRead: () => void) {
47+
return POST(
48+
new NextRequest(`http://localhost:3000/api/v2/workspaces/${WORKSPACE_ID}/source/plan`, {
49+
method: 'POST',
50+
headers: { 'x-api-key': 'key', 'content-type': 'application/json' },
51+
body: new ReadableStream(
52+
{
53+
pull() {
54+
onRead()
55+
return new Promise<void>(() => {})
56+
},
57+
},
58+
{ highWaterMark: 0 }
59+
),
60+
duplex: 'half',
61+
}),
62+
{ params: Promise.resolve({ workspaceId: WORKSPACE_ID }) }
63+
)
64+
}
65+
3466
const WORKFLOW = "// @sim-sdk 1\nexport default workflow('W', () => {})\n"
3567

3668
/** Units each limiter key was charged. */
@@ -48,6 +80,11 @@ function plan(files: Record<string, string>) {
4880
}
4981

5082
describe('POST /api/v2/workspaces/{workspaceId}/source/plan', () => {
83+
afterEach(() => {
84+
resetEnvMock()
85+
vi.useRealTimers()
86+
})
87+
5188
beforeEach(() => {
5289
charged.clear()
5390
v2RouteMocks.authenticate.mockResolvedValue(auth)
@@ -125,8 +162,11 @@ describe('POST /api/v2/workspaces/{workspaceId}/source/plan', () => {
125162
mocks.plan.mockImplementation(
126163
() => new Promise((resolve) => finish.push(() => resolve(result)))
127164
)
128-
// No declared length, so each reserves a body at the cap.
129-
const running = Array.from({ length: 4 }, () => plan({ 'workflows/a/workflow.ts': WORKFLOW }))
165+
// No declared length, so each reserves a body at the cap: four callers fill the lane.
166+
const running = Array.from({ length: 4 }, (_, caller) => {
167+
asCaller(`filler-${caller}`)
168+
return plan({ 'workflows/a/workflow.ts': WORKFLOW })
169+
})
130170
await vi.waitFor(() => expect(finish).toHaveLength(4))
131171

132172
let read = false
@@ -168,4 +208,62 @@ describe('POST /api/v2/workspaces/{workspaceId}/source/plan', () => {
168208
}
169209
expect((await plan({ 'workflows/a/workflow.ts': WORKFLOW })).status).toBe(200)
170210
})
211+
212+
it('answers 404 on the dedicated MCP host before admitting the caller or reading the body', async () => {
213+
const MCP_HOST = 'mcp.sim.test'
214+
setEnv({ SIM_MCP_URL: `https://${MCP_HOST}/mcp` })
215+
const request = new NextRequest(
216+
`http://${MCP_HOST}/api/v2/workspaces/${WORKSPACE_ID}/source/plan`,
217+
{
218+
method: 'POST',
219+
headers: { 'x-api-key': 'key', 'content-type': 'application/json', host: MCP_HOST },
220+
body: JSON.stringify({ files: {}, kinds: ['workflow'] }),
221+
}
222+
)
223+
224+
const response = await POST(request, { params: Promise.resolve({ workspaceId: WORKSPACE_ID }) })
225+
226+
expect(response.status).toBe(404)
227+
expect(request.bodyUsed).toBe(false)
228+
expect(v2RouteMocks.authenticate).not.toHaveBeenCalled()
229+
expect(mocks.plan).not.toHaveBeenCalled()
230+
})
231+
232+
it('holds one caller to a cap’s worth of bodies, so its burst leaves room for another caller', async () => {
233+
const result = await mocks.plan()
234+
const finish: Array<() => void> = []
235+
mocks.plan.mockImplementation(
236+
() => new Promise((resolve) => finish.push(() => resolve(result)))
237+
)
238+
// Each declares no length, so each would reserve a body at the cap.
239+
const burst = Array.from({ length: 4 }, () => plan({ 'workflows/a/workflow.ts': WORKFLOW }))
240+
await vi.waitFor(() => expect(finish).toHaveLength(1))
241+
242+
asCaller('other')
243+
const other = plan({ 'workflows/a/workflow.ts': WORKFLOW })
244+
await vi.waitFor(() => expect(finish).toHaveLength(2))
245+
for (const done of finish) done()
246+
247+
expect((await other).status).toBe(200)
248+
expect((await Promise.all(burst)).map((response) => response.status).sort()).toEqual([
249+
200, 429, 429, 429,
250+
])
251+
})
252+
253+
it('refuses a body that stalls past its read deadline with 408 and frees its room', async () => {
254+
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })
255+
let reading: () => void = () => {}
256+
const started = new Promise<void>((resolve) => {
257+
reading = resolve
258+
})
259+
const stalled = stalledPlan(reading)
260+
await started
261+
262+
await vi.advanceTimersByTimeAsync(5 * 60_000)
263+
264+
expect((await stalled).status).toBe(408)
265+
expect(mocks.plan).not.toHaveBeenCalled()
266+
// The same caller's next body at the cap is admitted: the stalled one no longer holds its room.
267+
expect((await plan({ 'workflows/a/workflow.ts': WORKFLOW })).status).toBe(200)
268+
})
171269
})

‎apps/sim/app/api/v2/workspaces/[workspaceId]/source/plan/route.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,9 @@ export const revalidate = 0
1818
* do, without writing: the dry run `sim workspaces source status` reads. Charged to the
1919
* source-plan budget as an apply is to the write budget (see `workspaceApplyRateCost`), so a
2020
* status never spends the source-write budget an apply needs. Plans run in their own slots: a
21-
* server already running as many plans as it allows answers 429, and applies never wait on them.
22-
* Answers 403 while the `workflow-code` flag is off.
21+
* server already running as many plans as it allows answers 429, and applies never wait on them;
22+
* so does a caller already sending a cap's worth of bodies. A body not received by its deadline
23+
* answers 408. Answers 403 while the `workflow-code` flag is off.
2324
*/
2425
export const POST = defineV2JsonRoute({
2526
contract: v2PlanWorkspaceSourceContract,

‎apps/sim/app/api/v2/workspaces/[workspaceId]/source/route.test.ts‎

Lines changed: 53 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,9 @@ import {
55
v2RateLimiterModuleMock,
66
v2RouteMocks,
77
} from '@sim/testing'
8+
import { resetEnvMock, setEnv } from '@sim/testing/mocks/env.mock'
89
import { NextRequest } from 'next/server'
9-
import { beforeEach, describe, expect, it, vi } from 'vitest'
10+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
1011

1112
const mocks = vi.hoisted(() => ({ apply: vi.fn(), read: vi.fn(), authorizeRead: vi.fn() }))
1213

@@ -57,6 +58,16 @@ function apply(
5758
)
5859
}
5960

61+
/** The next request is sent with a personal key of its own user, a caller apart from `auth`'s. */
62+
function asCaller(userId: string) {
63+
v2RouteMocks.authenticate.mockResolvedValueOnce({
64+
principal: { kind: 'personal_api_key', userId, keyId: `key-${userId}`, access: 'write' },
65+
rateLimitSubjectIds: [`api-key:key-${userId}`, `user:${userId}`],
66+
rateLimitSubscription: null,
67+
keyType: 'personal',
68+
})
69+
}
70+
6071
/** `count` errors of one workflow folder, as a plan refusal pins them to it. */
6172
function folderErrors(count: number): WorkspaceSourceDiagnostic[] {
6273
return Array.from({ length: count }, (_, index) => ({
@@ -146,9 +157,14 @@ describe('POST /api/v2/workspaces/{workspaceId}/source', () => {
146157
? new Promise((resolve) => finish.push(() => resolve(result)))
147158
: Promise.resolve({ ...result, dryRun: false })
148159
)
149-
const running = Array.from({ length: 4 }, () => apply('?dry=true'))
160+
// Four callers, as one caller holds no more than one body at the cap in a lane.
161+
const running = Array.from({ length: 4 }, (_, caller) => {
162+
asCaller(`planner-${caller}`)
163+
return apply('?dry=true')
164+
})
150165
await vi.waitFor(() => expect(finish).toHaveLength(4))
151166

167+
asCaller('one-more')
152168
expect((await apply('?dry=true')).status).toBe(429)
153169
expect((await apply('')).status).toBe(200)
154170

@@ -262,3 +278,38 @@ describe('GET /api/v2/workspaces/{workspaceId}/source', () => {
262278
expect(data.diagnostics.at(-1)).toMatchObject({ code: 'I_FINDINGS_TRUNCATED' })
263279
})
264280
})
281+
282+
describe('the workspace source routes on the dedicated MCP host', () => {
283+
const MCP_HOST = 'mcp.sim.test'
284+
285+
beforeEach(() => {
286+
setEnv({ SIM_MCP_URL: `https://${MCP_HOST}/mcp` })
287+
v2RouteMocks.authenticate.mockResolvedValue(auth)
288+
v2RouteMocks.preauthRate.mockResolvedValue(V2_PREAUTH_RATE_LIMIT_ALLOWED)
289+
v2RouteMocks.operationRate.mockResolvedValue(V2_OPERATION_RATE_LIMIT_ALLOWED)
290+
})
291+
292+
afterEach(() => {
293+
resetEnvMock()
294+
})
295+
296+
it('answers a get and an apply 404 before admitting the caller or reading the body', async () => {
297+
const url = `http://${MCP_HOST}/api/v2/workspaces/${WORKSPACE_ID}/source`
298+
const params = { params: Promise.resolve({ workspaceId: WORKSPACE_ID }) }
299+
const write = new NextRequest(url, {
300+
method: 'POST',
301+
headers: { 'x-api-key': 'key', 'content-type': 'application/json', host: MCP_HOST },
302+
body: JSON.stringify({ files: {}, kinds: ['workflow'] }),
303+
})
304+
305+
expect(
306+
(await GET(new NextRequest(url, { headers: { 'x-api-key': 'key', host: MCP_HOST } }), params))
307+
.status
308+
).toBe(404)
309+
expect((await POST(write, params)).status).toBe(404)
310+
expect(write.bodyUsed).toBe(false)
311+
expect(v2RouteMocks.authenticate).not.toHaveBeenCalled()
312+
expect(mocks.read).not.toHaveBeenCalled()
313+
expect(mocks.apply).not.toHaveBeenCalled()
314+
})
315+
})

‎apps/sim/app/api/v2/workspaces/[workspaceId]/source/route.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,8 @@ export const GET = defineV2JsonRoute({
5252
* written before it. A real apply draws on the source-write budget and a dry run, which writes
5353
* nothing, on the source-plan budget the status plan route uses (`v2RateLimits.sourceApply`), each
5454
* charged per workflow folder sent with its files (`workspaceApplyRateCost`), and runs in an apply
55-
* or a plan slot to match; a server already running as many as it allows answers 429.
55+
* or a plan slot to match; a server already running as many as it allows answers 429, as does a
56+
* caller already sending a cap's worth of bodies. A body not received by its deadline answers 408.
5657
*/
5758
export const POST = defineV2JsonRoute({
5859
contract: v2ApplyWorkspaceSourceContract,

‎apps/sim/lib/api/mcp/dispatch.test.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,21 @@ describe('dispatchMcpOperation', () => {
103103
expect(getOAuthAccessTokenAudience()).toEqual({})
104104
})
105105

106+
it('declares the length of the body it sends, so a route reserves only what it holds', async () => {
107+
await dispatchMcpOperation(
108+
{
109+
operation: 'completeFileUpload',
110+
params: { uploadId: 'up-1' },
111+
body: { workspaceId: 'wörkspace-1' },
112+
headers: { 'upload-token': 'token' },
113+
},
114+
context
115+
)
116+
const request = dispatched()
117+
const sent = new Uint8Array(await request.arrayBuffer())
118+
expect(request.headers.get('content-length')).toBe(String(sent.byteLength))
119+
})
120+
106121
it.each([
107122
[{ tableId: 't' }, 'Missing path parameter rowId.'],
108123
[{ tableId: 't', rowId: 'r', extra: 'x' }, 'Unknown path parameter extra'],

‎apps/sim/lib/api/mcp/dispatch.ts‎

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -81,14 +81,21 @@ function resolvePath(
8181
}
8282
}
8383

84-
/** The dispatched request's headers: inherited context, the verified credential, and caller-settable contract headers. */
84+
/**
85+
* The dispatched request's headers: inherited context, the verified credential, caller-settable
86+
* contract headers, and the body's type and length, so a route that reserves room for a body
87+
* before reading it reserves what this one holds.
88+
*/
8589
function buildHeaders(
8690
call: McpOperationCall,
8791
context: McpDispatchContext,
88-
hasBody: boolean
92+
body: string | undefined
8993
): Headers | { error: string } {
9094
const headers = new Headers({ accept: 'application/json', [CLIENT_INFO_HEADER]: 'mcp' })
91-
if (hasBody) headers.set('content-type', 'application/json')
95+
if (body !== undefined) {
96+
headers.set('content-type', 'application/json')
97+
headers.set('content-length', String(new TextEncoder().encode(body).byteLength))
98+
}
9299
for (const name of INHERITED_HEADERS) {
93100
const value = context.inbound.headers.get(name)
94101
if (value) headers.set(name, value)
@@ -208,7 +215,8 @@ export async function dispatchMcpRequest(
208215
'Streaming is not supported over MCP. Omit stream to wait for the result, or set async: true and poll getWorkflowRun.',
209216
}
210217
}
211-
const headers = buildHeaders(call, context, hasBody)
218+
const body = hasBody ? JSON.stringify(call.body ?? {}) : undefined
219+
const headers = buildHeaders(call, context, body)
212220
if ('error' in headers) return { rejected: headers.error }
213221

214222
const route = await handler()
@@ -219,7 +227,7 @@ export async function dispatchMcpRequest(
219227
const request = new NextRequest(url, {
220228
method: contract.method,
221229
headers,
222-
body: hasBody ? JSON.stringify(call.body ?? {}) : undefined,
230+
body,
223231
signal: context.signal,
224232
})
225233
const response = await withOAuthAccessTokenAudience(context.audience, () =>

‎apps/sim/lib/api/server/routes/types.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,16 @@ export interface JsonErrorResponseDescriptor {
4242
headers?: HeadersInit
4343
}
4444

45+
/**
46+
* Room a route holds for a request's body from before it is read until the request is answered:
47+
* `release` frees it, however the request ends, and a body not read within `readDeadlineMs` is
48+
* refused so a stalled upload cannot keep it.
49+
*/
50+
export interface BodyReservation {
51+
release(): void
52+
readDeadlineMs: number
53+
}
54+
4555
export interface JsonRouteDefinition<
4656
C extends JsonApiRouteContract,
4757
O extends ApplicationOperation,

0 commit comments

Comments
 (0)