Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion apps/sim/lib/execution/payloads/cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
43 changes: 43 additions & 0 deletions apps/sim/lib/execution/payloads/large-array-manifest.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand Down
10 changes: 7 additions & 3 deletions apps/sim/lib/execution/payloads/materialization.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,18 +150,22 @@ 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<unknown | undefined> {
): Promise<{ value: unknown; bytes: number } | undefined> {
const log = getLogger(options)
if (!isLargeValueRef(ref) || !ref.key || !isValidLargeValueKey(ref)) {
return undefined
}

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')
Expand All @@ -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({
Expand Down
26 changes: 25 additions & 1 deletion apps/sim/lib/execution/payloads/store.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down Expand Up @@ -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',
Expand Down
10 changes: 5 additions & 5 deletions apps/sim/lib/execution/payloads/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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,
Expand Down
5 changes: 3 additions & 2 deletions apps/sim/lib/uploads/utils/user-file-base64.server.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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')
})
Expand Down
2 changes: 1 addition & 1 deletion apps/sim/lib/workflows/executor/execution-core.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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({
Expand Down
Loading