Skip to content

Commit f28435c

Browse files
authored
fix(execution): bound large-value reads by their declared size (#10322)
- Cap storage downloads at ref.size and reject anything larger - Refuse cached values larger than the ref claims - Cache storage reads by measured bytes, not the caller's declared size
1 parent 1f76338 commit f28435c

7 files changed

Lines changed: 86 additions & 13 deletions

File tree

‎apps/sim/lib/execution/payloads/cache.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -185,7 +185,8 @@ export function materializeLargeValueRefSync(
185185
): unknown {
186186
cleanupExpiredValues()
187187
const cached = inMemoryValues.get(ref.id)
188-
if (!cached || !scopeMatchesRef(ref, cached.scope, callerScope)) {
188+
// Callers admit reads by the declared size, so never serve a value larger than the ref claims.
189+
if (!cached || cached.size > ref.size || !scopeMatchesRef(ref, cached.scope, callerScope)) {
189190
return undefined
190191
}
191192
// Idle-TTL touch on every authorized read: refresh expiry and move the entry

‎apps/sim/lib/execution/payloads/large-array-manifest.test.ts‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,49 @@ describe('large array manifests', () => {
143143
).rejects.toThrow('Invalid large array manifest')
144144
})
145145

146+
describe('forged chunk sizes', () => {
147+
const items = [{ id: 1, payload: 'x'.repeat(2048) }]
148+
const readOptions = { ...TEST_CONTEXT, maxBytes: 1024 * 1024 }
149+
150+
/** Repeats one real chunk while declaring 1 byte each; creating it leaves the chunk cached. */
151+
async function forgeRepeatedChunkManifest() {
152+
const manifest = await createLargeArrayManifest(items, TEST_CONTEXT)
153+
const [chunk] = manifest.chunks
154+
const repeats = 4
155+
const forged = {
156+
...manifest,
157+
totalCount: chunk.count * repeats,
158+
chunkCount: repeats,
159+
byteSize: repeats,
160+
chunks: Array.from({ length: repeats }, () => ({
161+
ref: { ...chunk.ref, size: 1 },
162+
count: chunk.count,
163+
byteSize: 1,
164+
})),
165+
}
166+
expect(isLargeArrayManifest(forged)).toBe(true)
167+
return forged
168+
}
169+
170+
it('does not download chunks larger than their declared size', async () => {
171+
const forged = await forgeRepeatedChunkManifest()
172+
clearLargeValueCacheForTests()
173+
mockDownloadFile.mockResolvedValue(Buffer.from(JSON.stringify(items), 'utf8'))
174+
175+
await expect(materializeLargeArrayManifest(forged, readOptions)).rejects.toThrow(
176+
'Large array manifest chunk is unavailable'
177+
)
178+
})
179+
180+
it('does not serve cached chunks larger than their declared size', async () => {
181+
const forged = await forgeRepeatedChunkManifest()
182+
183+
await expect(materializeLargeArrayManifest(forged, readOptions)).rejects.toThrow(
184+
'Large array manifest chunk is unavailable'
185+
)
186+
})
187+
})
188+
146189
it('rejects manifests whose chunk count does not match materialized data', async () => {
147190
const manifest = await createLargeArrayManifest([{ id: 1 }], TEST_CONTEXT)
148191
const forgedManifest = {

‎apps/sim/lib/execution/payloads/materialization.server.ts‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -150,18 +150,22 @@ export function assertLargeValueRefAccess(
150150
}
151151
}
152152

153+
/**
154+
* Downloads and parses a durable large value. Callers admit reads by the declared `ref.size`, so
155+
* the stored bytes may never exceed it; `bytes` is the measured length for cache accounting.
156+
*/
153157
export async function readLargeValueRefFromStorage(
154158
ref: LargeValueRef,
155159
options: MaterializeLargeValueOptions = {}
156-
): Promise<unknown | undefined> {
160+
): Promise<{ value: unknown; bytes: number } | undefined> {
157161
const log = getLogger(options)
158162
if (!isLargeValueRef(ref) || !ref.key || !isValidLargeValueKey(ref)) {
159163
return undefined
160164
}
161165

162166
assertLargeValueRefAccess(ref, options)
163167
assertInlineMaterializationSize(ref.size, options.maxBytes)
164-
const maxBytes = options.maxBytes ?? MAX_INLINE_MATERIALIZATION_BYTES
168+
const maxBytes = ref.size
165169

166170
try {
167171
const { StorageService } = await import('@/lib/uploads')
@@ -177,7 +181,7 @@ export async function readLargeValueRefFromStorage(
177181
limitBytes: maxBytes,
178182
})
179183
}
180-
return JSON.parse(buffer.toString('utf8'))
184+
return { value: JSON.parse(buffer.toString('utf8')), bytes: buffer.length }
181185
} catch (error) {
182186
if (isPayloadSizeLimitError(error)) {
183187
throw new ExecutionResourceLimitError({

‎apps/sim/lib/execution/payloads/store.test.ts‎

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -501,7 +501,7 @@ describe('large execution payload store', () => {
501501
allowLargeValueWorkflowScope: true,
502502
}
503503
)
504-
).resolves.toEqual({ ok: true })
504+
).resolves.toEqual({ value: { ok: true }, bytes: 11 })
505505
})
506506

507507
it('does not materialize forged keyless refs from another cached execution', () => {
@@ -576,6 +576,30 @@ describe('large execution payload store', () => {
576576
expect(mockDownloadFile).not.toHaveBeenCalled()
577577
})
578578

579+
it('caches storage reads by measured bytes so an inflated ref cannot lock out the true ref', async () => {
580+
const scope = {
581+
workspaceId: 'workspace-1',
582+
workflowId: 'workflow-1',
583+
executionId: 'execution-1',
584+
}
585+
const stored = JSON.stringify({ ok: true })
586+
const ref = {
587+
__simLargeValueRef: true,
588+
version: 1,
589+
id: 'lv_MEASURED1234',
590+
kind: 'object',
591+
size: Buffer.byteLength(stored, 'utf8'),
592+
key: 'execution/workspace-1/workflow-1/execution-1/large-value-lv_MEASURED1234.json',
593+
executionId: 'execution-1',
594+
} as const
595+
mockDownloadFile.mockResolvedValueOnce(Buffer.from(stored, 'utf8'))
596+
597+
await expect(materializeLargeValueRef({ ...ref, size: 4096 }, scope)).resolves.toEqual({
598+
ok: true,
599+
})
600+
expect(materializeLargeValueRefSync(ref, scope)).toEqual({ ok: true })
601+
})
602+
579603
it('fails loudly when reference tracking fails before returning cached durable refs', async () => {
580604
const scope = {
581605
workspaceId: 'workspace-1',

‎apps/sim/lib/execution/payloads/store.ts‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -277,7 +277,7 @@ export async function materializeLargeValueRef(
277277
return cached
278278
}
279279

280-
const value = await readLargeValueRefFromStorage(ref, {
280+
const stored = await readLargeValueRefFromStorage(ref, {
281281
workspaceId: context.workspaceId,
282282
workflowId: context.workflowId,
283283
executionId: context.executionId,
@@ -287,20 +287,20 @@ export async function materializeLargeValueRef(
287287
userId: context.userId,
288288
maxBytes: context.maxBytes ?? ref.size,
289289
})
290-
if (value === undefined) {
290+
if (stored === undefined) {
291291
return undefined
292292
}
293293
cacheLargeValue(
294294
ref.id,
295-
value,
296-
ref.size,
295+
stored.value,
296+
stored.bytes,
297297
{
298298
...context,
299299
executionId: ref.executionId ?? context.executionId,
300300
},
301301
{ recoverable: true }
302302
)
303-
return value
303+
return stored.value
304304
} catch (error) {
305305
logger.warn('Failed to materialize persisted large execution value', {
306306
id: ref.id,

‎apps/sim/lib/uploads/utils/user-file-base64.server.test.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -270,19 +270,20 @@ describe('hydrateUserFilesWithBase64', () => {
270270
type: 'text/plain',
271271
context: 'execution',
272272
}
273+
const storedValue = Buffer.from(JSON.stringify({ file }), 'utf8')
273274
const ref = {
274275
__simLargeValueRef: true,
275276
version: 1,
276277
id: 'lv_ABCDEFGHIJKL',
277278
kind: 'object',
278-
size: 256,
279+
size: storedValue.length,
279280
key: 'execution/workspace/workflow/source-execution/large-value-lv_ABCDEFGHIJKL.json',
280281
executionId: 'source-execution',
281282
}
282283

283284
mockDownloadFile.mockImplementation(async ({ key }) => {
284285
if (key.includes('large-value')) {
285-
return Buffer.from(JSON.stringify({ file }), 'utf8')
286+
return storedValue
286287
}
287288
return Buffer.from('hello', 'utf8')
288289
})

‎apps/sim/lib/workflows/executor/execution-core.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1082,7 +1082,7 @@ describe('executeWorkflowCore terminal finalization sequencing', () => {
10821082
expect(result.success).toBe(true)
10831083
expect(executorExecuteMock).toHaveBeenCalledOnce()
10841084
expect(downloadFileMock).toHaveBeenCalledWith(
1085-
expect.objectContaining({ key: manifest.chunks[0].ref.key, maxBytes: 64 * 1024 * 1024 })
1085+
expect.objectContaining({ key: manifest.chunks[0].ref.key, maxBytes: sourceBytes.length })
10861086
)
10871087
expect(uploadFileMock).toHaveBeenCalledWith(
10881088
expect.objectContaining({

0 commit comments

Comments
 (0)