Skip to content

Commit a061b18

Browse files
committed
fix(workflow-code): gate file() paths on files.use, match names as written, and report truncation exactly
- a path the stored workflow does not already hold resolves only for a caller whose group allows Files; any other caller gets the unknown-file finding a missing path gets - resolve file() paths by exact name and folder path instead of the VFS reference parser, so files named content or meta.json inside a folder resolve - read file pages until the manifest cap is filled so files no path names cannot hide a truncated list - document the quoted file('docs/report.pdf') form in the manifest description
1 parent 796fe00 commit a061b18

8 files changed

Lines changed: 172 additions & 56 deletions

File tree

‎apps/docs/openapi-v2-workflows.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23931,7 +23931,7 @@
2393123931
"items": {
2393223932
"type": "string"
2393323933
},
23934-
"description": "Workspace files by folder path and name (`docs/report.pdf`), as `file(path)` names them, oldest upload first."
23934+
"description": "Workspace files by folder path and name (`docs/report.pdf`), each named in source as `file('docs/report.pdf')`, oldest upload first."
2393523935
},
2393623936
"env": {
2393723937
"type": "array",

‎apps/sim/lib/api/contracts/v2/source-resources.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,7 @@ const sourceResourcesSchema = z
111111
files: z
112112
.array(z.string())
113113
.describe(
114-
'Workspace files by folder path and name (`docs/report.pdf`), as `file(path)` names them, oldest upload first.'
114+
"Workspace files by folder path and name (`docs/report.pdf`), each named in source as `file('docs/report.pdf')`, oldest upload first."
115115
),
116116
env: z
117117
.array(z.string())

‎apps/sim/lib/uploads/contexts/workspace/file-manager.ts‎

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2486,31 +2486,39 @@ async function listWorkspaceFileCandidates(
24862486
}
24872487

24882488
/**
2489-
* Live workspace files by id, by storage key, and by reference (resolved as
2489+
* Live workspace files by id, by storage key, by exact name in any folder (`names`, taken as
2490+
* written rather than as a VFS path), and by reference (resolved as
24902491
* {@link findListedWorkspaceFiles} resolves it), from one read and one folder-path hydration.
24912492
* `files` holds each match once, oldest upload first. Another workspace's ids and keys, deleted
24922493
* files, chat uploads, and owned files never match.
24932494
*/
24942495
export async function lookupActiveWorkspaceFiles(
24952496
workspaceId: string,
2496-
lookup: { ids: readonly string[]; keys: readonly string[]; references: readonly string[] }
2497+
lookup: {
2498+
ids: readonly string[]
2499+
keys: readonly string[]
2500+
names?: readonly string[]
2501+
references: readonly string[]
2502+
}
24972503
): Promise<{ files: WorkspaceFileRecord[]; references: Map<string, WorkspaceFileRecord | null> }> {
2498-
if (lookup.ids.length + lookup.keys.length + lookup.references.length === 0) {
2504+
const names = new Set(lookup.names)
2505+
if (lookup.ids.length + lookup.keys.length + names.size + lookup.references.length === 0) {
24992506
return { files: [], references: new Map() }
25002507
}
25012508
const byReference = referenceCandidates(lookup.references)
25022509
const candidates = await listWorkspaceFileCandidates(workspaceId, {
25032510
ids: [...lookup.ids, ...byReference.ids],
25042511
keys: lookup.keys,
2505-
leafNames: byReference.leafNames,
2512+
leafNames: [...byReference.leafNames, ...[...names].map(normalizeDisplaySegment)],
25062513
})
25072514
const references = resolveListedReferences(candidates, lookup.references)
25082515
const ids = new Set(lookup.ids)
25092516
const keys = new Set(lookup.keys)
25102517
const resolved = new Set([...references.values()].map((file) => file?.id))
25112518
return {
25122519
files: candidates.filter(
2513-
(file) => ids.has(file.id) || keys.has(file.key) || resolved.has(file.id)
2520+
(file) =>
2521+
ids.has(file.id) || keys.has(file.key) || names.has(file.name) || resolved.has(file.id)
25142522
),
25152523
references,
25162524
}

‎apps/sim/lib/workflows/application/read-source-resources.integration.ts‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ import { featureFlagsMock, featureFlagsMockFns } from '@sim/testing/mocks/featur
3535
import { generateId } from '@sim/utils/id'
3636
import { eq, inArray } from 'drizzle-orm'
3737
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest'
38+
import { MAX_MANIFEST_RESOURCES_PER_KIND } from '@/lib/api/contracts/v2/source-resources'
3839
import { readSourceResources } from '@/lib/workflows/application/read-source-resources'
3940

4041
vi.mock('@/lib/core/config/feature-flags', () => featureFlagsMock)
@@ -528,4 +529,36 @@ describe('source resources manifest', () => {
528529
expect(manifest.env).toEqual([])
529530
})
530531
})
532+
533+
it('marks the files section truncated when a file no path names sits among the first page', async () => {
534+
const before = Date.now() - 60 * 60 * 1000
535+
const rows = Array.from({ length: MAX_MANIFEST_RESOURCES_PER_KIND + 1 }, (_, index) => ({
536+
id: generateId(),
537+
key: `workspace/${workspaceId}/bulk-${index}`,
538+
userId: adminId,
539+
workspaceId,
540+
context: 'workspace',
541+
originalName: index === 0 ? 'a/b.txt' : `bulk-${index}.txt`,
542+
contentType: 'text/plain',
543+
sizeBytes: 1,
544+
uploadedAt: new Date(before + index),
545+
}))
546+
await db.insert(workspaceFiles).values(rows)
547+
try {
548+
const manifest = await readSourceResources.execute({
549+
principal: session(adminId),
550+
input: { workspaceId },
551+
})
552+
expect(manifest.files).toHaveLength(MAX_MANIFEST_RESOURCES_PER_KIND)
553+
expect(manifest.files).not.toContain('plan.md')
554+
expect(manifest.truncated).toBe(true)
555+
} finally {
556+
await db.delete(workspaceFiles).where(
557+
inArray(
558+
workspaceFiles.id,
559+
rows.map((row) => row.id)
560+
)
561+
)
562+
}
563+
})
531564
})

‎apps/sim/lib/workflows/application/read-source-resources.ts‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -265,7 +265,7 @@ export const readSourceResources = defineAuthorizedWorkspaceUseCase({
265265
skillRows,
266266
customToolRows,
267267
mcpServerRows,
268-
filePaths,
268+
files,
269269
env,
270270
] = await Promise.all([
271271
visible.tables
@@ -326,7 +326,9 @@ export const readSourceResources = defineAuthorizedWorkspaceUseCase({
326326
.orderBy(asc(mcpServers.createdAt), asc(mcpServers.id))
327327
.limit(PAGE)
328328
: [],
329-
visible.files ? loadWorkspaceFilePaths(workspaceId, PAGE) : [],
329+
visible.files
330+
? loadWorkspaceFilePaths(workspaceId, MAX_MANIFEST_RESOURCES_PER_KIND)
331+
: { paths: [], truncated: false },
330332
visible.env ? loadEnvNames(workspaceId, userId, access) : [],
331333
])
332334

@@ -337,7 +339,6 @@ export const readSourceResources = defineAuthorizedWorkspaceUseCase({
337339
const skills = capped(skillRows)
338340
const tools = capped(customToolRows)
339341
const servers = capped(mcpServerRows)
340-
const files = capped(filePaths)
341342

342343
const refs: ResourceIdRef[] = [
343344
...tables.rows.map((row) => ({ kind: 'table' as const, id: row.id })),
@@ -387,7 +388,7 @@ export const readSourceResources = defineAuthorizedWorkspaceUseCase({
387388
const names = mcpTools.get(server.id)
388389
return names ? { ...server, tools: names } : server
389390
}),
390-
files: files.rows,
391+
files: files.paths,
391392
env,
392393
truncated: [tables, kbs, credentials, workflows, skills, tools, servers, files].some(
393394
(section) => section.truncated

‎apps/sim/lib/workflows/application/source-pipeline/evaluate/resolve.ts‎

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -180,7 +180,19 @@ export async function resolveSubmission(
180180
collectResourceKeys(block, compiledKeys, span)
181181
}
182182
const storedResources = resources
183-
const newKeys = compiledKeys.filter(({ kind, key }) => storedResources.toId(kind, key) === null)
183+
let filesWithheld: Promise<boolean> | undefined
184+
// permission-group-enforced: files.use — a path the stored workflow does not hold names a file only for a caller the file list serves; for any other it names no file
185+
const isFilesWithheld = () =>
186+
(filesWithheld ??= isWorkspaceCapabilityWithheld(
187+
scope.subjectUserId,
188+
scope.workspaceId,
189+
'files.use',
190+
scope.workspaceOrganizationId
191+
))
192+
let newKeys = compiledKeys.filter(({ kind, key }) => storedResources.toId(kind, key) === null)
193+
if (newKeys.some(({ kind }) => kind === 'file') && (await isFilesWithheld())) {
194+
newKeys = newKeys.filter(({ kind }) => kind !== 'file')
195+
}
184196
if (newKeys.length > 0) {
185197
const extra = await loadResourceKeyResolver(
186198
scope.workspaceId,
@@ -263,15 +275,7 @@ export async function resolveSubmission(
263275
.map(({ kind }) => kind)
264276
// As in the source resources manifest, file paths stay unlisted when the caller's group
265277
// withholds Files.
266-
if (
267-
missingKinds.includes('file') &&
268-
(await isWorkspaceCapabilityWithheld(
269-
scope.subjectUserId,
270-
scope.workspaceId,
271-
'files.use',
272-
scope.workspaceOrganizationId
273-
))
274-
) {
278+
if (missingKinds.includes('file') && (await isFilesWithheld())) {
275279
missingKinds = missingKinds.filter((kind) => kind !== 'file')
276280
}
277281
if (missingKinds.length > 0) {

‎apps/sim/lib/workflows/code/resources.ts‎

Lines changed: 29 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,10 @@ import { credentialAccessClause, credentialMembershipJoin } from '@/lib/credenti
88
import { getWorkspaceEnvironmentVariableNames } from '@/lib/environment/utils'
99
import {
1010
lookupActiveWorkspaceFiles,
11+
type QueryWorkspaceFilesOptions,
1112
queryWorkspaceFiles,
1213
type WorkspaceFileRecord,
1314
} from '@/lib/uploads/contexts/workspace/file-manager'
14-
import { encodeVfsPathSegments, VfsPathError } from '@/lib/vfs/path'
1515
import { isBuiltinSkillId } from '@/lib/workflows/skills/builtin-skills'
1616
import { workspaceFileSourcePath } from '@/lib/workspace-files/folder-display-path'
1717
import { checkWorkspaceAccess, type WorkspaceAccess } from '@/lib/workspaces/permissions/utils'
@@ -138,20 +138,6 @@ async function loadSkillNames(workspaceId: string, ids: string[]): Promise<Map<s
138138
const credentialIdsOf = (refs: ResourceIdRef[]) =>
139139
refs.flatMap((ref) => (ref.kind === 'credential' ? [ref.id] : []))
140140

141-
/**
142-
* `path` in the VFS form a file reference is read in (`files/` prefix stripped, segments
143-
* percent-decoded), so its folder and file names resolve exactly as written; `null` for a path
144-
* with an empty or dot segment, which names no file.
145-
*/
146-
function vfsReference(path: string): string | null {
147-
try {
148-
return `files/${encodeVfsPathSegments(path.split('/'))}`
149-
} catch (error) {
150-
if (error instanceof VfsPathError) return null
151-
throw error
152-
}
153-
}
154-
155141
/**
156142
* The live workspace files `references` name: by the id or storage key a stored file-upload
157143
* object carries (`stored`) and by source path (`paths`), each file under its source path.
@@ -163,13 +149,13 @@ async function loadReferencedFiles(
163149
): Promise<Map<string, WorkspaceFileRecord>> {
164150
const byPath = new Map<string, WorkspaceFileRecord>()
165151
if (stored.length === 0 && paths.length === 0) return byPath
152+
// A path is matched as written, never read as a VFS path: `docs/content` names a file
153+
// called `content`, not the folder `docs`.
166154
const { files } = await lookupActiveWorkspaceFiles(workspaceId, {
167155
ids: stored,
168156
keys: stored,
169-
references: paths.flatMap((path) => {
170-
const reference = vfsReference(path)
171-
return reference === null ? [] : [reference]
172-
}),
157+
names: paths.flatMap((path) => path.split('/').at(-1) || []),
158+
references: [],
173159
})
174160
for (const file of files) {
175161
const path = workspaceFileSourcePath(file)
@@ -289,7 +275,8 @@ export async function loadAvailableResourceKeys(
289275
const entries = await Promise.all(
290276
[...new Set(kinds)].map(async (kind) => {
291277
if (kind === 'file') {
292-
return [kind, await loadWorkspaceFilePaths(workspaceId, AVAILABLE_KEYS_LIMIT)] as const
278+
const { paths } = await loadWorkspaceFilePaths(workspaceId, AVAILABLE_KEYS_LIMIT)
279+
return [kind, paths] as const
293280
}
294281
const rows = await listLiveKeys(workspaceId, kind, { limit: AVAILABLE_KEYS_LIMIT })
295282
if (kind !== 'credential') return [kind, rows.map((row) => row.key)] as const
@@ -306,22 +293,32 @@ export async function loadAvailableResourceKeys(
306293

307294
/**
308295
* The source paths (`file('<path>')`) of up to `limit` of the workspace's live files, oldest upload
309-
* first; a file no slash-separated path names is left out.
296+
* first, and whether more follow; a file no slash-separated path names is left out, so pages are
297+
* read until `limit` paths are found or none remain.
310298
*/
311299
export async function loadWorkspaceFilePaths(
312300
workspaceId: string,
313301
limit: number
314-
): Promise<string[]> {
315-
const { files } = await queryWorkspaceFiles(workspaceId, {
316-
scope: 'active',
317-
sortBy: 'uploadedAt',
318-
sortOrder: 'asc',
319-
limit,
320-
})
321-
return files.flatMap((file) => {
322-
const path = workspaceFileSourcePath(file)
323-
return path === null ? [] : [path]
324-
})
302+
): Promise<{ paths: string[]; truncated: boolean }> {
303+
const paths: string[] = []
304+
let after: QueryWorkspaceFilesOptions['after']
305+
for (;;) {
306+
const page = await queryWorkspaceFiles(workspaceId, {
307+
scope: 'active',
308+
sortBy: 'uploadedAt',
309+
sortOrder: 'asc',
310+
limit: limit + 1 - paths.length,
311+
after,
312+
})
313+
for (const file of page.files) {
314+
const path = workspaceFileSourcePath(file)
315+
if (path !== null) paths.push(path)
316+
}
317+
if (paths.length > limit || page.nextKeys === null) {
318+
return { paths: paths.slice(0, limit), truncated: paths.length > limit }
319+
}
320+
after = page.nextKeys
321+
}
325322
}
326323

327324
/** `idsByKey` without the credential keys bound to a credential `userId` cannot see. */

‎apps/sim/lib/workspace-source/application/files.integration.ts‎

Lines changed: 76 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -216,12 +216,12 @@ async function storedFileInput(workflowId: string): Promise<unknown> {
216216
return block?.subBlocks.readFile?.value
217217
}
218218

219-
/** A workflow whose file block reads `reference` (source text, e.g. `file('a.txt')`). */
220-
function fileReader(reference: string): string {
219+
/** A workflow named `name` whose file block reads `reference` (source text, e.g. `file('a.txt')`). */
220+
function fileReader(reference: string, name = 'Path reader'): string {
221221
return `// @sim-sdk 1
222222
import { file, trigger, workflow } from '@sim/workflow-sdk'
223223
224-
export default workflow('Path reader', {}, () => {
224+
export default workflow('${name}', {}, () => {
225225
const start = trigger.start('Start', { inputFormat: {} })
226226
const read = file.read('Read', { readFileInput: ${reference}, folderIncludeSubfolders: true })
227227
start.to(read)
@@ -1108,6 +1108,79 @@ export default workflow('Reader', {}, () => {
11081108
}
11091109
)
11101110

1111+
check(
1112+
'a member whose permission group withholds Files names no file by path, as for a missing one, yet keeps the file a workflow holds',
1113+
async () => {
1114+
const workspaceId = await newWorkspace()
1115+
const held = await uploadInUi(workspaceId, 'moved', 'a.txt', 'held by the workflow')
1116+
await uploadInUi(workspaceId, 'moved', 'b.txt', 'withheld from the member')
1117+
const applied = await workflowsOnly.apply(workspaceId, {
1118+
files: { 'workflows/path-reader/workflow.ts': fileReader("file('moved/a.txt')") },
1119+
})
1120+
if (applied.failed) throw new Error('The owner could not name the file')
1121+
const workflowId = applied.base.resources['workflow:path-reader']?.id
1122+
if (!workflowId) throw new Error('The apply wrote no workflow')
1123+
await withholdFilesFromBlocked(workspaceId)
1124+
1125+
const refusedAs = async (path: string) => {
1126+
const refused = await refusal(
1127+
workflowsOnly.apply(workspaceId, {
1128+
files: { 'workflows/lost/workflow.ts': fileReader(`file('${path}')`, 'Lost') },
1129+
principal: blocked,
1130+
})
1131+
)
1132+
const errors = refused.diagnostics.flatMap(({ severity, code, message, hint }) =>
1133+
severity === 'error' ? [{ code, message: message.replace(path, '<path>'), hint }] : []
1134+
)
1135+
expect(errors.map((finding) => finding.code)).toEqual(['E_MAT_UNKNOWN_RESOURCE'])
1136+
return errors
1137+
}
1138+
expect(await refusedAs('moved/b.txt')).toEqual(await refusedAs('moved/c.txt'))
1139+
1140+
const read = await workflowsOnly.get(workspaceId, blocked)
1141+
const printed = read.files['workflows/path-reader/workflow.ts']
1142+
if (printed === undefined) throw new Error('The get printed no workflow')
1143+
const kept = await workflowsOnly.apply(workspaceId, {
1144+
files: {
1145+
...read.files,
1146+
'workflows/path-reader/workflow.ts': printed.replace("'Read'", "'Read held file'"),
1147+
},
1148+
base: read.base,
1149+
principal: blocked,
1150+
})
1151+
expect(kept.failed).toBeUndefined()
1152+
expect(summary(kept.applied)).toEqual(['update path-reader'])
1153+
expect(await storedFileInput(workflowId)).toMatchObject({ id: held.id, key: held.key })
1154+
}
1155+
)
1156+
1157+
check(
1158+
'a file path names a file called content or meta.json, and a folder called content, as written',
1159+
async () => {
1160+
const workspaceId = await newWorkspace()
1161+
const named = [
1162+
['docs', 'content'],
1163+
['docs', 'meta.json'],
1164+
['content', 'a.txt'],
1165+
['', 'content'],
1166+
] as const
1167+
for (const [index, [folderPath, name]] of named.entries()) {
1168+
const stored = await uploadInUi(workspaceId, folderPath, name, `${folderPath}/${name}`)
1169+
const path = folderPath ? `${folderPath}/${name}` : name
1170+
const source = `workflows/reader-${index}/workflow.ts`
1171+
const applied = await workflowsOnly.apply(workspaceId, {
1172+
files: { [source]: fileReader(`file('${path}')`, `Reader ${index}`) },
1173+
})
1174+
expect(applied.failed).toBeUndefined()
1175+
const workflowId = applied.base.resources[`workflow:reader-${index}`]?.id
1176+
if (!workflowId) throw new Error(`The apply naming ${path} wrote no workflow`)
1177+
expect(await storedFileInput(workflowId)).toMatchObject({ id: stored.id, key: stored.key })
1178+
const printed = (await workflowsOnly.get(workspaceId)).files[source]
1179+
expect(printed).toContain(`readFileInput: file('${path}')`)
1180+
}
1181+
}
1182+
)
1183+
11111184
check(
11121185
'a declared file the server can no longer hand to source since the get refuses only a directory that changes it',
11131186
async () => {

0 commit comments

Comments
 (0)