Skip to content

Commit c3748ab

Browse files
authored
fix(integrations): validate mongodb, neo4j and upstash (#10172)
* fix(integrations): validate postgresql, mysql, mongodb, neo4j and upstash * fix(integrations): stream neo4j records under the cap, keep mysql preferred tls as documented, tune truncation hints * fix(integrations): drop the row cap; stream mongodb and neo4j reads and fail at the response size limit
1 parent 340861b commit c3748ab

24 files changed

Lines changed: 274 additions & 46 deletions

‎apps/sim/lib/internal/mongodb/execute-tool.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { getErrorMessage } from '@sim/utils/errors'
22
import type { z } from 'zod'
3+
import { isPayloadSizeLimitError } from '@/lib/core/utils/stream-limits'
34
import {
45
executeMongodbAggregation,
56
executeMongodbDelete,
@@ -40,6 +41,7 @@ async function executeOperation<TInput>(
4041
return Response.json(result)
4142
} catch (error) {
4243
signal?.throwIfAborted()
44+
if (isPayloadSizeLimitError(error)) throw error
4345
if (error instanceof MongodbOperationInputError) {
4446
return Response.json({ error: error.message }, { status: 400 })
4547
}

‎apps/sim/lib/internal/mongodb/operations.ts‎

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -23,9 +23,25 @@ import type {
2323
MongodbQueryInput,
2424
MongodbUpdateInput,
2525
} from '@/lib/internal/mongodb/schema'
26+
import { createResponseRowsBudget } from '@/lib/internal/tool-operations/response-limits'
2627

2728
export class MongodbOperationInputError extends Error {}
2829

30+
/**
31+
* Reads documents one at a time, failing with the tool response size error as soon as they cannot
32+
* fit the response. Leaving the loop early closes the server cursor, so an oversized result is
33+
* never read into memory in full.
34+
*/
35+
async function readDocuments(cursor: AsyncIterable<Document>, toolId: string) {
36+
const budget = createResponseRowsBudget(toolId)
37+
const documents: Document[] = []
38+
for await (const document of cursor) {
39+
budget.admit(document)
40+
documents.push(document)
41+
}
42+
return documents
43+
}
44+
2945
async function withMongodbClient<TResult>(
3046
input: MongodbConnectionConfig,
3147
signal: AbortSignal | undefined,
@@ -71,7 +87,7 @@ export function executeMongodbQuery(input: MongodbQueryInput, signal?: AbortSign
7187
}
7288

7389
cursor = cursor.limit(input.limit || 100)
74-
const documents = await cursor.toArray()
90+
const documents = await readDocuments(cursor, 'mongodb_query')
7591
signal?.throwIfAborted()
7692
return {
7793
message: `Found ${documents.length} documents`,
@@ -92,11 +108,10 @@ export function executeMongodbAggregation(input: MongodbExecuteInput, signal?: A
92108
const pipeline = JSON.parse(input.pipeline) as Document[]
93109

94110
return withMongodbClient(input, signal, async (client) => {
95-
const documents = await client
96-
.db(input.database)
97-
.collection(collectionName)
98-
.aggregate(pipeline, { signal })
99-
.toArray()
111+
const documents = await readDocuments(
112+
client.db(input.database).collection(collectionName).aggregate(pipeline, { signal }),
113+
'mongodb_execute'
114+
)
100115
signal?.throwIfAborted()
101116
return {
102117
message: `Aggregation completed, returned ${documents.length} documents`,

‎apps/sim/lib/internal/neo4j/execute-tool.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import {
99
neo4jQueryContract,
1010
neo4jUpdateContract,
1111
} from '@/lib/api/contracts/tools/databases/neo4j'
12+
import { isPayloadSizeLimitError } from '@/lib/core/utils/stream-limits'
1213
import {
1314
executeNeo4jCreate,
1415
executeNeo4jDelete,
@@ -35,6 +36,7 @@ async function executeOperation<C extends AnyApiRouteContract>(
3536
return Response.json(await execute(parsed.data, signal))
3637
} catch (error) {
3738
signal?.throwIfAborted()
39+
if (isPayloadSizeLimitError(error)) throw error
3840
if (error instanceof Neo4jOperationInputError) {
3941
return Response.json({ error: `Query validation failed: ${error.message}` }, { status: 400 })
4042
}

‎apps/sim/lib/internal/neo4j/operations.test.ts‎

Lines changed: 46 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ vi.mock('@/lib/internal/neo4j/client', () => ({
1111
createNeo4jDriver: mocks.createDriver,
1212
}))
1313

14+
import { isPayloadSizeLimitError } from '@/lib/core/utils/stream-limits'
1415
import { executeNeo4jQuery, Neo4jOperationInputError } from '@/lib/internal/neo4j/operations'
1516

1617
const INPUT = {
@@ -24,7 +25,8 @@ const INPUT = {
2425
parameters: {},
2526
}
2627

27-
function queryResult() {
28+
/** A driver `Result` streaming `count` records, recording whether the rest was discarded. */
29+
function streamingResult(count: number, value = 'Ada') {
2830
const updates = {
2931
nodesCreated: 0,
3032
nodesDeleted: 0,
@@ -38,19 +40,32 @@ function queryResult() {
3840
constraintsAdded: 0,
3941
constraintsRemoved: 0,
4042
}
43+
const summary = {
44+
resultAvailableAfter: { toNumber: () => 2 },
45+
resultConsumedAfter: { toNumber: () => 3 },
46+
counters: { updates: () => updates },
47+
}
48+
const state = { pulled: 0, discarded: false }
49+
const record = { keys: ['name'], get: () => value }
4150
return {
42-
records: [{ keys: ['name'], get: vi.fn().mockReturnValue('Ada') }],
43-
summary: {
44-
resultAvailableAfter: { toNumber: () => 2 },
45-
resultConsumedAfter: { toNumber: () => 3 },
46-
counters: { updates: () => updates },
47-
},
51+
state,
52+
[Symbol.asyncIterator]: () => ({
53+
next: async () => {
54+
if (state.pulled >= count) return { done: true, value: summary }
55+
state.pulled++
56+
return { done: false, value: record }
57+
},
58+
return: async () => {
59+
state.discarded = true
60+
return { done: true, value: summary }
61+
},
62+
}),
4863
}
4964
}
5065

5166
describe('Neo4j operations', () => {
5267
beforeEach(() => {
53-
mocks.run.mockResolvedValue(queryResult())
68+
mocks.run.mockImplementation(() => streamingResult(1))
5469
mocks.sessionClose.mockResolvedValue(undefined)
5570
mocks.driverClose.mockResolvedValue(undefined)
5671
mocks.createDriver.mockResolvedValue({
@@ -59,6 +74,29 @@ describe('Neo4j operations', () => {
5974
})
6075
})
6176

77+
it('returns every record of a result that fits the response limit', async () => {
78+
const result = streamingResult(20_000)
79+
mocks.run.mockReturnValue(result)
80+
81+
const response = await executeNeo4jQuery(INPUT)
82+
83+
expect(response).toMatchObject({ recordCount: 20_000, summary: { resultAvailableAfter: 2 } })
84+
expect(result.state.discarded).toBe(false)
85+
})
86+
87+
it('fails with the response size error and discards the rest once records cannot fit', async () => {
88+
const result = streamingResult(1_000, 'x'.repeat(64 * 1024))
89+
mocks.run.mockReturnValue(result)
90+
91+
const error = await executeNeo4jQuery(INPUT).catch((caught: unknown) => caught)
92+
93+
expect(isPayloadSizeLimitError(error)).toBe(true)
94+
expect(error).toMatchObject({ label: 'neo4j_query response body' })
95+
expect(result.state.discarded).toBe(true)
96+
expect(result.state.pulled).toBeLessThan(1_000)
97+
expect(mocks.sessionClose).toHaveBeenCalled()
98+
})
99+
62100
it('rejects invalid Cypher before opening a driver', async () => {
63101
await expect(executeNeo4jQuery({ ...INPUT, cypherQuery: ' ' })).rejects.toBeInstanceOf(
64102
Neo4jOperationInputError

‎apps/sim/lib/internal/neo4j/operations.ts‎

Lines changed: 42 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { createLogger } from '@sim/logger'
2-
import type { QueryResult, Session } from 'neo4j-driver'
2+
import type { Record as Neo4jRecord, Result, ResultSummary, Session } from 'neo4j-driver'
33
import type {
44
Neo4jCreateRequest,
55
Neo4jDeleteRequest,
@@ -11,6 +11,7 @@ import type {
1111
} from '@/lib/api/contracts/tools/databases/neo4j'
1212
import { createNeo4jDriver } from '@/lib/internal/neo4j/client'
1313
import { convertNeo4jValue } from '@/lib/internal/neo4j/values'
14+
import { createResponseRowsBudget } from '@/lib/internal/tool-operations/response-limits'
1415
import type { Neo4jNodeSchema, Neo4jRelationshipSchema } from '@/tools/neo4j/types'
1516

1617
const logger = createLogger('Neo4jOperations')
@@ -43,21 +44,44 @@ function bindSessionAbort(session: Session, signal?: AbortSignal): () => void {
4344
return () => signal.removeEventListener('abort', abort)
4445
}
4546

46-
function projectRecords(result: QueryResult): Array<Record<string, unknown>> {
47-
return result.records.map((record) => {
48-
const projected: Record<string, unknown> = {}
49-
for (const key of record.keys) {
50-
if (typeof key === 'string') projected[key] = convertNeo4jValue(record.get(key))
47+
function projectRecord(record: Neo4jRecord): Record<string, unknown> {
48+
const projected: Record<string, unknown> = {}
49+
for (const key of record.keys) {
50+
if (typeof key === 'string') projected[key] = convertNeo4jValue(record.get(key))
51+
}
52+
return projected
53+
}
54+
55+
/**
56+
* Streams the records, failing with the tool response size error as soon as they cannot fit the
57+
* response. Returning the iterator early tells the server to discard the rest, so an oversized
58+
* result is never buffered in full. `delete` returns no records, so it only waits for the summary.
59+
*/
60+
async function readResult(result: Result, kind: StatementKind) {
61+
if (kind === 'delete') return { records: [], summary: await result.summary() }
62+
const budget = createResponseRowsBudget(`neo4j_${kind}`)
63+
const records: Array<Record<string, unknown>> = []
64+
const iterator = result[Symbol.asyncIterator]()
65+
try {
66+
let next = await iterator.next()
67+
while (!next.done) {
68+
const projected = projectRecord(next.value)
69+
budget.admit(projected)
70+
records.push(projected)
71+
next = await iterator.next()
5172
}
52-
return projected
53-
})
73+
return { records, summary: next.value }
74+
} catch (error) {
75+
await iterator.return?.().catch(() => undefined)
76+
throw error
77+
}
5478
}
5579

56-
function projectSummary(result: QueryResult) {
57-
const updates = result.summary.counters.updates()
80+
function projectSummary(summary: ResultSummary) {
81+
const updates = summary.counters.updates()
5882
return {
59-
resultAvailableAfter: result.summary.resultAvailableAfter.toNumber(),
60-
resultConsumedAfter: result.summary.resultConsumedAfter.toNumber(),
83+
resultAvailableAfter: summary.resultAvailableAfter.toNumber(),
84+
resultConsumedAfter: summary.resultConsumedAfter.toNumber(),
6185
counters: {
6286
nodesCreated: updates.nodesCreated,
6387
nodesDeleted: updates.nodesDeleted,
@@ -74,9 +98,11 @@ function projectSummary(result: QueryResult) {
7498
}
7599
}
76100

77-
function statementResponse(kind: StatementKind, result: QueryResult) {
78-
const records = projectRecords(result)
79-
const summary = projectSummary(result)
101+
function statementResponse(
102+
kind: StatementKind,
103+
{ records, summary: resultSummary }: Awaited<ReturnType<typeof readResult>>
104+
) {
105+
const summary = projectSummary(resultSummary)
80106
switch (kind) {
81107
case 'query':
82108
return {
@@ -128,7 +154,7 @@ async function executeStatement(input: StatementInput, kind: StatementKind, sign
128154
const session = driver.session({ database: input.database })
129155
const unbindAbort = bindSessionAbort(session, signal)
130156
try {
131-
const result = await session.run(input.cypherQuery, input.parameters ?? {})
157+
const result = await readResult(session.run(input.cypherQuery, input.parameters ?? {}), kind)
132158
signal?.throwIfAborted()
133159
return statementResponse(kind, result)
134160
} finally {
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
import { describe, expect, it } from 'vitest'
2+
import { isPayloadSizeLimitError } from '@/lib/core/utils/stream-limits'
3+
import {
4+
createResponseRowsBudget,
5+
MAX_TOOL_RESPONSE_BODY_BYTES,
6+
} from '@/lib/internal/tool-operations/response-limits'
7+
8+
/** Admits every row, returning the error the budget threw, if any. */
9+
function admitAll(rows: unknown[]): unknown {
10+
const budget = createResponseRowsBudget('test_tool')
11+
try {
12+
for (const row of rows) budget.admit(row)
13+
return undefined
14+
} catch (error) {
15+
return error
16+
}
17+
}
18+
19+
describe('response rows budget', () => {
20+
it('admits any number of rows while their array still fits the response limit', () => {
21+
expect(admitAll(Array.from({ length: 50_000 }, (_, id) => ({ id })))).toBeUndefined()
22+
})
23+
24+
it('fails exactly where the serialized array passes the response limit', () => {
25+
const fitting = ['x'.repeat(MAX_TOOL_RESPONSE_BODY_BYTES - 4)]
26+
expect(Buffer.byteLength(JSON.stringify(fitting))).toBe(MAX_TOOL_RESPONSE_BODY_BYTES)
27+
expect(admitAll(fitting)).toBeUndefined()
28+
29+
const error = admitAll(['x'.repeat(MAX_TOOL_RESPONSE_BODY_BYTES - 3)])
30+
expect(isPayloadSizeLimitError(error)).toBe(true)
31+
expect(error).toMatchObject({
32+
label: 'test_tool response body',
33+
maxBytes: MAX_TOOL_RESPONSE_BODY_BYTES,
34+
})
35+
})
36+
37+
it('counts UTF-8 bytes, so multibyte text fails on its encoded size', () => {
38+
const row = '漢'.repeat(MAX_TOOL_RESPONSE_BODY_BYTES / 3)
39+
expect(row.length).toBeLessThan(MAX_TOOL_RESPONSE_BODY_BYTES)
40+
expect(isPayloadSizeLimitError(admitAll([row]))).toBe(true)
41+
})
42+
})
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,28 @@
1+
import { PayloadSizeLimitError } from '@/lib/core/utils/stream-limits'
2+
13
/** Maximum inline tool response size; binary file outputs use stored descriptors. */
24
export const MAX_TOOL_RESPONSE_BODY_BYTES = 10 * 1024 * 1024
5+
6+
/**
7+
* Fails a streamed result as soon as its serialized rows alone exceed
8+
* {@link MAX_TOOL_RESPONSE_BODY_BYTES}. Bytes are counted the way the response serializes them
9+
* (UTF-8, plus the array's brackets and commas), and the body around the rows is larger still, so
10+
* this fails exactly the results the executor's response limit would reject, but before the rest
11+
* of the result is read into memory. The error is the same one that limit throws.
12+
*/
13+
export function createResponseRowsBudget(toolId: string) {
14+
let bytes = 1
15+
return {
16+
admit(row: unknown): void {
17+
const serialized = JSON.stringify(row)
18+
bytes += (serialized === undefined ? 4 : Buffer.byteLength(serialized, 'utf8')) + 1
19+
if (bytes > MAX_TOOL_RESPONSE_BODY_BYTES) {
20+
throw new PayloadSizeLimitError({
21+
label: `${toolId} response body`,
22+
maxBytes: MAX_TOOL_RESPONSE_BODY_BYTES,
23+
observedBytes: bytes,
24+
})
25+
}
26+
},
27+
}
28+
}

‎apps/sim/tools/upstash/redis_delete.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { UPSTASH_CREDENTIAL_OAUTH } from '@/tools/shared/saved-credentials'
22
import type { ToolConfig } from '@/tools/types'
33
import type { UpstashRedisDeleteParams, UpstashRedisDeleteResponse } from '@/tools/upstash/types'
4+
import { upstashPathSegment } from '@/tools/upstash/utils'
45

56
export const upstashRedisDeleteTool: ToolConfig<
67
UpstashRedisDeleteParams,
@@ -34,7 +35,7 @@ export const upstashRedisDeleteTool: ToolConfig<
3435
},
3536

3637
request: {
37-
url: (params) => `${params.restUrl}/del/${encodeURIComponent(params.key)}`,
38+
url: (params) => `${params.restUrl}/del/${upstashPathSegment(params.key, 'key')}`,
3839
method: 'POST',
3940
headers: (params) => ({
4041
Authorization: `Bearer ${params.restToken}`,

‎apps/sim/tools/upstash/redis_exists.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { UPSTASH_CREDENTIAL_OAUTH } from '@/tools/shared/saved-credentials'
22
import type { ToolConfig } from '@/tools/types'
33
import type { UpstashRedisExistsParams, UpstashRedisExistsResponse } from '@/tools/upstash/types'
4+
import { upstashPathSegment } from '@/tools/upstash/utils'
45

56
export const upstashRedisExistsTool: ToolConfig<
67
UpstashRedisExistsParams,
@@ -35,7 +36,7 @@ export const upstashRedisExistsTool: ToolConfig<
3536
},
3637

3738
request: {
38-
url: (params) => `${params.restUrl}/exists/${encodeURIComponent(params.key)}`,
39+
url: (params) => `${params.restUrl}/exists/${upstashPathSegment(params.key, 'key')}`,
3940
method: 'GET',
4041
headers: (params) => ({
4142
Authorization: `Bearer ${params.restToken}`,

‎apps/sim/tools/upstash/redis_expire.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { UPSTASH_CREDENTIAL_OAUTH } from '@/tools/shared/saved-credentials'
22
import type { ToolConfig } from '@/tools/types'
33
import type { UpstashRedisExpireParams, UpstashRedisExpireResponse } from '@/tools/upstash/types'
4+
import { upstashInteger, upstashPathSegment } from '@/tools/upstash/utils'
45

56
export const upstashRedisExpireTool: ToolConfig<
67
UpstashRedisExpireParams,
@@ -40,7 +41,8 @@ export const upstashRedisExpireTool: ToolConfig<
4041
},
4142

4243
request: {
43-
url: (params) => `${params.restUrl}/expire/${encodeURIComponent(params.key)}/${params.seconds}`,
44+
url: (params) =>
45+
`${params.restUrl}/expire/${upstashPathSegment(params.key, 'key')}/${upstashInteger(params.seconds, 'seconds')}`,
4446
method: 'GET',
4547
headers: (params) => ({
4648
Authorization: `Bearer ${params.restToken}`,

0 commit comments

Comments
 (0)