diff --git a/apps/sim/lib/execution/payloads/cache.ts b/apps/sim/lib/execution/payloads/cache.ts index 55462de08dd..9db3a73de0f 100644 --- a/apps/sim/lib/execution/payloads/cache.ts +++ b/apps/sim/lib/execution/payloads/cache.ts @@ -185,7 +185,8 @@ export function materializeLargeValueRefSync( ): unknown { cleanupExpiredValues() const cached = inMemoryValues.get(ref.id) - if (!cached || !scopeMatchesRef(ref, cached.scope, callerScope)) { + // Callers admit reads by the declared size, so never serve a value larger than the ref claims. + if (!cached || cached.size > ref.size || !scopeMatchesRef(ref, cached.scope, callerScope)) { return undefined } // Idle-TTL touch on every authorized read: refresh expiry and move the entry diff --git a/apps/sim/lib/execution/payloads/large-array-manifest.test.ts b/apps/sim/lib/execution/payloads/large-array-manifest.test.ts index cb3c249b878..3642648cf7b 100644 --- a/apps/sim/lib/execution/payloads/large-array-manifest.test.ts +++ b/apps/sim/lib/execution/payloads/large-array-manifest.test.ts @@ -143,6 +143,49 @@ describe('large array manifests', () => { ).rejects.toThrow('Invalid large array manifest') }) + describe('forged chunk sizes', () => { + const items = [{ id: 1, payload: 'x'.repeat(2048) }] + const readOptions = { ...TEST_CONTEXT, maxBytes: 1024 * 1024 } + + /** Repeats one real chunk while declaring 1 byte each; creating it leaves the chunk cached. */ + async function forgeRepeatedChunkManifest() { + const manifest = await createLargeArrayManifest(items, TEST_CONTEXT) + const [chunk] = manifest.chunks + const repeats = 4 + const forged = { + ...manifest, + totalCount: chunk.count * repeats, + chunkCount: repeats, + byteSize: repeats, + chunks: Array.from({ length: repeats }, () => ({ + ref: { ...chunk.ref, size: 1 }, + count: chunk.count, + byteSize: 1, + })), + } + expect(isLargeArrayManifest(forged)).toBe(true) + return forged + } + + it('does not download chunks larger than their declared size', async () => { + const forged = await forgeRepeatedChunkManifest() + clearLargeValueCacheForTests() + mockDownloadFile.mockResolvedValue(Buffer.from(JSON.stringify(items), 'utf8')) + + await expect(materializeLargeArrayManifest(forged, readOptions)).rejects.toThrow( + 'Large array manifest chunk is unavailable' + ) + }) + + it('does not serve cached chunks larger than their declared size', async () => { + const forged = await forgeRepeatedChunkManifest() + + await expect(materializeLargeArrayManifest(forged, readOptions)).rejects.toThrow( + 'Large array manifest chunk is unavailable' + ) + }) + }) + it('rejects manifests whose chunk count does not match materialized data', async () => { const manifest = await createLargeArrayManifest([{ id: 1 }], TEST_CONTEXT) const forgedManifest = { diff --git a/apps/sim/lib/execution/payloads/materialization.server.ts b/apps/sim/lib/execution/payloads/materialization.server.ts index b52dbc871ee..63df7818f58 100644 --- a/apps/sim/lib/execution/payloads/materialization.server.ts +++ b/apps/sim/lib/execution/payloads/materialization.server.ts @@ -150,10 +150,14 @@ export function assertLargeValueRefAccess( } } +/** + * Downloads and parses a durable large value. Callers admit reads by the declared `ref.size`, so + * the stored bytes may never exceed it; `bytes` is the measured length for cache accounting. + */ export async function readLargeValueRefFromStorage( ref: LargeValueRef, options: MaterializeLargeValueOptions = {} -): Promise { +): Promise<{ value: unknown; bytes: number } | undefined> { const log = getLogger(options) if (!isLargeValueRef(ref) || !ref.key || !isValidLargeValueKey(ref)) { return undefined @@ -161,7 +165,7 @@ export async function readLargeValueRefFromStorage( assertLargeValueRefAccess(ref, options) assertInlineMaterializationSize(ref.size, options.maxBytes) - const maxBytes = options.maxBytes ?? MAX_INLINE_MATERIALIZATION_BYTES + const maxBytes = ref.size try { const { StorageService } = await import('@/lib/uploads') @@ -177,7 +181,7 @@ export async function readLargeValueRefFromStorage( limitBytes: maxBytes, }) } - return JSON.parse(buffer.toString('utf8')) + return { value: JSON.parse(buffer.toString('utf8')), bytes: buffer.length } } catch (error) { if (isPayloadSizeLimitError(error)) { throw new ExecutionResourceLimitError({ diff --git a/apps/sim/lib/execution/payloads/store.test.ts b/apps/sim/lib/execution/payloads/store.test.ts index 0e4bac3a88c..6c0a13367ab 100644 --- a/apps/sim/lib/execution/payloads/store.test.ts +++ b/apps/sim/lib/execution/payloads/store.test.ts @@ -501,7 +501,7 @@ describe('large execution payload store', () => { allowLargeValueWorkflowScope: true, } ) - ).resolves.toEqual({ ok: true }) + ).resolves.toEqual({ value: { ok: true }, bytes: 11 }) }) it('does not materialize forged keyless refs from another cached execution', () => { @@ -576,6 +576,30 @@ describe('large execution payload store', () => { expect(mockDownloadFile).not.toHaveBeenCalled() }) + it('caches storage reads by measured bytes so an inflated ref cannot lock out the true ref', async () => { + const scope = { + workspaceId: 'workspace-1', + workflowId: 'workflow-1', + executionId: 'execution-1', + } + const stored = JSON.stringify({ ok: true }) + const ref = { + __simLargeValueRef: true, + version: 1, + id: 'lv_MEASURED1234', + kind: 'object', + size: Buffer.byteLength(stored, 'utf8'), + key: 'execution/workspace-1/workflow-1/execution-1/large-value-lv_MEASURED1234.json', + executionId: 'execution-1', + } as const + mockDownloadFile.mockResolvedValueOnce(Buffer.from(stored, 'utf8')) + + await expect(materializeLargeValueRef({ ...ref, size: 4096 }, scope)).resolves.toEqual({ + ok: true, + }) + expect(materializeLargeValueRefSync(ref, scope)).toEqual({ ok: true }) + }) + it('fails loudly when reference tracking fails before returning cached durable refs', async () => { const scope = { workspaceId: 'workspace-1', diff --git a/apps/sim/lib/execution/payloads/store.ts b/apps/sim/lib/execution/payloads/store.ts index b59416371cf..dbd67d3a2da 100644 --- a/apps/sim/lib/execution/payloads/store.ts +++ b/apps/sim/lib/execution/payloads/store.ts @@ -277,7 +277,7 @@ export async function materializeLargeValueRef( return cached } - const value = await readLargeValueRefFromStorage(ref, { + const stored = await readLargeValueRefFromStorage(ref, { workspaceId: context.workspaceId, workflowId: context.workflowId, executionId: context.executionId, @@ -287,20 +287,20 @@ export async function materializeLargeValueRef( userId: context.userId, maxBytes: context.maxBytes ?? ref.size, }) - if (value === undefined) { + if (stored === undefined) { return undefined } cacheLargeValue( ref.id, - value, - ref.size, + stored.value, + stored.bytes, { ...context, executionId: ref.executionId ?? context.executionId, }, { recoverable: true } ) - return value + return stored.value } catch (error) { logger.warn('Failed to materialize persisted large execution value', { id: ref.id, diff --git a/apps/sim/lib/uploads/utils/user-file-base64.server.test.ts b/apps/sim/lib/uploads/utils/user-file-base64.server.test.ts index 8fccb04b209..cac1c4ea7e7 100644 --- a/apps/sim/lib/uploads/utils/user-file-base64.server.test.ts +++ b/apps/sim/lib/uploads/utils/user-file-base64.server.test.ts @@ -270,19 +270,20 @@ describe('hydrateUserFilesWithBase64', () => { type: 'text/plain', context: 'execution', } + const storedValue = Buffer.from(JSON.stringify({ file }), 'utf8') const ref = { __simLargeValueRef: true, version: 1, id: 'lv_ABCDEFGHIJKL', kind: 'object', - size: 256, + size: storedValue.length, key: 'execution/workspace/workflow/source-execution/large-value-lv_ABCDEFGHIJKL.json', executionId: 'source-execution', } mockDownloadFile.mockImplementation(async ({ key }) => { if (key.includes('large-value')) { - return Buffer.from(JSON.stringify({ file }), 'utf8') + return storedValue } return Buffer.from('hello', 'utf8') }) diff --git a/apps/sim/lib/workflows/executor/execution-core.test.ts b/apps/sim/lib/workflows/executor/execution-core.test.ts index 5a851be9493..810090f6912 100644 --- a/apps/sim/lib/workflows/executor/execution-core.test.ts +++ b/apps/sim/lib/workflows/executor/execution-core.test.ts @@ -1082,7 +1082,7 @@ describe('executeWorkflowCore terminal finalization sequencing', () => { expect(result.success).toBe(true) expect(executorExecuteMock).toHaveBeenCalledOnce() expect(downloadFileMock).toHaveBeenCalledWith( - expect.objectContaining({ key: manifest.chunks[0].ref.key, maxBytes: 64 * 1024 * 1024 }) + expect.objectContaining({ key: manifest.chunks[0].ref.key, maxBytes: sourceBytes.length }) ) expect(uploadFileMock).toHaveBeenCalledWith( expect.objectContaining({