Skip to content

Commit cdac23d

Browse files
authored
fix(workflow-code): release review follow-ups for the knowledge download cap, regex hardening and skill docs (#10304)
Knowledge original downloads accept documents up to the 100 MiB stored-document limit instead of the 25 MiB extraction cap. Three regexes that ran in polynomial time on long inputs (source-status trailing slashes, compile hint builder prefix, codegen layout reference chains) are linear, and the codegen reference pattern escapes its input. Skill and rule docs name the right path and valueType().
1 parent 92aee6b commit cdac23d

21 files changed

Lines changed: 234 additions & 55 deletions

File tree

‎.agents/skills/add-column-type/SKILL.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -145,8 +145,8 @@ Copy `currency`'s service function and orchestration branch.
145145

146146
The workspace source table codec reads the registry, but the SDK restates each type: add the
147147
`column.<type>()` helper to `packages/workflow-sdk/src/workspace/table.d.ts` (the drift test in
148-
`lib/workspace-source/application/kinds/table/codec.test.ts` fails until you do), map the type's row
149-
value in `columnType()` (`packages/workflow-sdk/src/codegen/workspace.ts`, which defaults to
148+
`apps/sim/lib/workspace-source/application/kinds/table/codec.test.ts` fails until you do), map the
149+
type's row value in `valueType()` (`packages/workflow-sdk/src/codegen/workspace.ts`, which defaults to
150150
`string`), and regenerate the embedded text (`bun packages/workflow-sdk/scripts/generate-embedded-text.ts`).
151151
See `.claude/rules/sim-workflow-code.md`.
152152

‎.claude/rules/sim-workflow-code.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -134,7 +134,7 @@ Follow `/add-column-type`. The workspace codec reads the column registry
134134
- the `column.<type>()` helper in `packages/workflow-sdk/src/workspace/table.d.ts`
135135
(`kinds/table/codec.test.ts` fails until it exists), then regenerate the embedded text
136136
(`bun packages/workflow-sdk/scripts/generate-embedded-text.ts`);
137-
- `columnType()` in `packages/workflow-sdk/src/codegen/workspace.ts`, the row type `table('k')`
137+
- `valueType()` in `packages/workflow-sdk/src/codegen/workspace.ts`, the row type `table('k')`
138138
gives, which defaults to `string`;
139139
- a type that owns metadata: `TABLE_COLUMN_METADATA_KEYS` in
140140
`packages/workspace-code/src/kinds/table.ts` plus the reader and printer there.

‎.cursor/rules/sim-workflow-code.mdc‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,7 @@ Follow `/add-column-type`. The workspace codec reads the column registry
114114
- the `column.<type>()` helper in `packages/workflow-sdk/src/workspace/table.d.ts`
115115
(`kinds/table/codec.test.ts` fails until it exists), then regenerate the embedded text
116116
(`bun packages/workflow-sdk/scripts/generate-embedded-text.ts`);
117-
- `columnType()` in `packages/workflow-sdk/src/codegen/workspace.ts`, the row type `table('k')`
117+
- `valueType()` in `packages/workflow-sdk/src/codegen/workspace.ts`, the row type `table('k')`
118118
gives, which defaults to `string`;
119119
- a type that owns metadata: `TABLE_COLUMN_METADATA_KEYS` in
120120
`packages/workspace-code/src/kinds/table.ts` plus the reader and printer there.

‎.github/workflows/publish-sim-cli.yml‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,9 @@ on:
77
- 'packages/sim-cli/**'
88
# The build bundles its workspace dependencies, so a change there
99
# changes what ships. `bun run check:sim-cli-bundle` fails when this
10-
# list and the bundle's workspace packages disagree.
10+
# list and the bundle's workspace packages disagree. bun.lock is not
11+
# watched: nearly every lockfile change leaves the bundle byte-identical,
12+
# and the next change to a watched package ships the ones that do not.
1113
- 'packages/table-cells/**'
1214
- 'packages/utils/**'
1315
- 'packages/workflow-code/**'

‎apps/sim/app/api/v2/knowledge/[knowledgeBaseId]/documents/[documentId]/content/route.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { v2KnowledgeErrorPolicies } from '@/lib/knowledge/api/route-policies'
55
import { knowledgeOperations } from '@/lib/knowledge/application/operations'
66
import { readOriginalKnowledgeDocument } from '@/lib/knowledge/application/read-original-document'
77
import { encodeFilenameForHeader } from '@/lib/uploads/server/delivery'
8+
import { MAX_KNOWLEDGE_DOCUMENT_FILE_SIZE } from '@/lib/uploads/shared/types'
89

910
export const dynamic = 'force-dynamic'
1011
export const revalidate = 0
@@ -14,8 +15,9 @@ export const revalidate = 0
1415
* original bytes.
1516
*
1617
* What `sim workspaces source get` downloads for each document of a knowledge base. A document
17-
* whose original is not stored (a connector-synced page) answers `NOT_FOUND`. `headSafe: false`
18-
* because the read pulls the bytes out of object storage.
18+
* whose original is not stored (a connector-synced page) answers `NOT_FOUND`. Nothing parses the
19+
* bytes, so any original up to the stored-document limit downloads, not just those under the
20+
* text-extraction cap. `headSafe: false` because the read pulls the bytes out of object storage.
1921
*/
2022
export const GET = defineV2BinaryRoute({
2123
contract: v2DownloadKnowledgeDocumentContract,
@@ -28,6 +30,7 @@ export const GET = defineV2BinaryRoute({
2830
knowledgeBaseId: params.knowledgeBaseId,
2931
documentId: params.documentId,
3032
assertedWorkspaceId: query.workspaceId,
33+
maxBytes: MAX_KNOWLEDGE_DOCUMENT_FILE_SIZE,
3134
}),
3235
useCase: readOriginalKnowledgeDocument,
3336
present: (document) => {
Lines changed: 124 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,124 @@
1+
/**
2+
* The v2 knowledge document download route against real PostgreSQL and local object storage,
3+
* through its route handler with a real workspace API key. A download parses nothing, so it serves
4+
* any stored original up to the stored-document limit, including one past the text-extraction cap
5+
* that a parsing read refuses.
6+
*/
7+
import { mkdtempSync } from 'node:fs'
8+
import { rm } from 'node:fs/promises'
9+
import { tmpdir } from 'node:os'
10+
import path from 'node:path'
11+
import { db } from '@sim/db'
12+
import { apiKey, document, knowledgeBase, organization, user, workspace } from '@sim/db/schema'
13+
import { deleteWorkspaceFixture } from '@sim/db/testing/workspace-fixtures'
14+
import { generateId } from '@sim/utils/id'
15+
import { eq, inArray } from 'drizzle-orm'
16+
import { NextRequest } from 'next/server'
17+
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
18+
19+
const fixtureStorage = vi.hoisted(() => ({ root: '' }))
20+
vi.mock('@/lib/uploads/core/setup.server', () => ({
21+
get UPLOAD_DIR_SERVER() {
22+
return fixtureStorage.root
23+
},
24+
}))
25+
26+
import { hashApiKey } from '@/lib/api-key/crypto'
27+
import {
28+
createKnowledgeAclFixtureIds,
29+
seedKnowledgeAclFixture,
30+
} from '@/lib/knowledge/__integration__/seed-source-access-fixture'
31+
import { uploadFile } from '@/lib/uploads/core/storage-service'
32+
import { MAX_KNOWLEDGE_DOCUMENT_FILE_SIZE } from '@/lib/uploads/shared/types'
33+
import { MAX_TEXT_EXTRACTION_BYTES } from '@/lib/uploads/utils/file'
34+
import { GET } from '@/app/api/v2/knowledge/[knowledgeBaseId]/documents/[documentId]/content/route'
35+
36+
const ids = createKnowledgeAclFixtureIds()
37+
const key = `sk-sim-fixture-${generateId()}`
38+
39+
async function seedStoredDocument(bytes: Buffer, fileSize = bytes.byteLength) {
40+
const id = generateId()
41+
const storageKey = `kb/${id}.bin`
42+
await uploadFile({
43+
file: bytes,
44+
fileName: 'original.bin',
45+
contentType: 'application/octet-stream',
46+
context: 'knowledge-base',
47+
customKey: storageKey,
48+
preserveKey: true,
49+
persistMetadata: false,
50+
})
51+
await db.insert(document).values({
52+
id,
53+
knowledgeBaseId: ids.knowledgeBaseId,
54+
filename: 'original.bin',
55+
fileUrl: '',
56+
storageKey,
57+
fileSize,
58+
mimeType: 'application/octet-stream',
59+
processingStatus: 'completed',
60+
acl: ['ws'],
61+
aclRequirements: [],
62+
aclVerifiedAt: new Date(),
63+
})
64+
return id
65+
}
66+
67+
function download(documentId: string) {
68+
const request = new NextRequest(
69+
`http://localhost:3000/api/v2/knowledge/${ids.knowledgeBaseId}/documents/${documentId}/content?workspaceId=${ids.workspaceId}`,
70+
{ headers: { 'x-api-key': key, 'x-forwarded-for': '127.0.0.1' } }
71+
)
72+
return GET(request, {
73+
params: Promise.resolve({ knowledgeBaseId: ids.knowledgeBaseId, documentId }),
74+
})
75+
}
76+
77+
beforeAll(async () => {
78+
fixtureStorage.root = mkdtempSync(path.join(tmpdir(), 'sim-knowledge-download-'))
79+
await seedKnowledgeAclFixture(ids)
80+
await db.insert(apiKey).values({
81+
id: generateId(),
82+
userId: ids.aliceId,
83+
workspaceId: ids.workspaceId,
84+
createdBy: ids.aliceId,
85+
name: 'Download fixture',
86+
key,
87+
keyHash: hashApiKey(key),
88+
type: 'workspace',
89+
access: 'read',
90+
})
91+
})
92+
93+
afterAll(async () => {
94+
await db.delete(knowledgeBase).where(eq(knowledgeBase.id, ids.knowledgeBaseId))
95+
await deleteWorkspaceFixture(db, eq(workspace.id, ids.workspaceId))
96+
await db.delete(organization).where(eq(organization.id, ids.organizationId))
97+
await db.delete(user).where(inArray(user.id, [ids.aliceId, ids.bobId]))
98+
await rm(fixtureStorage.root, { recursive: true, force: true })
99+
await db.$client.end()
100+
})
101+
102+
describe('GET /api/v2/knowledge/[knowledgeBaseId]/documents/[documentId]/content', () => {
103+
it('downloads an original larger than the text-extraction cap', async () => {
104+
const bytes = Buffer.alloc(MAX_TEXT_EXTRACTION_BYTES + 1024 * 1024, 'k')
105+
const documentId = await seedStoredDocument(bytes)
106+
107+
const response = await download(documentId)
108+
109+
expect(response.status).toBe(200)
110+
expect(response.headers.get('content-length')).toBe(String(bytes.byteLength))
111+
expect(Buffer.from(await response.arrayBuffer()).equals(bytes)).toBe(true)
112+
})
113+
114+
it('refuses a document recorded past the stored-document limit', async () => {
115+
const documentId = await seedStoredDocument(
116+
Buffer.from('small'),
117+
MAX_KNOWLEDGE_DOCUMENT_FILE_SIZE + 1
118+
)
119+
120+
const response = await download(documentId)
121+
122+
expect(response.status).toBe(413)
123+
})
124+
})

‎apps/sim/lib/knowledge/application/read-original-document.ts‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,12 +14,17 @@ import {
1414
} from '@/lib/knowledge/secret-provenance'
1515
import { isObjectNotFoundError } from '@/lib/uploads/core/errors'
1616
import { downloadFile } from '@/lib/uploads/core/storage-service'
17+
import { MAX_KNOWLEDGE_DOCUMENT_FILE_SIZE } from '@/lib/uploads/shared/types'
1718
import { MAX_TEXT_EXTRACTION_BYTES } from '@/lib/uploads/utils/file'
1819

1920
export interface ReadOriginalKnowledgeDocumentInput {
2021
knowledgeBaseId: string
2122
documentId: string
2223
assertedWorkspaceId: string
24+
/**
25+
* Largest original the read accepts. Defaults to the text-extraction cap, for a caller that
26+
* parses the bytes; a raw download raises it up to the stored-document limit.
27+
*/
2328
maxBytes?: number
2429
signal?: AbortSignal
2530
}
@@ -41,7 +46,11 @@ export const readOriginalKnowledgeDocument = defineAuthorizedKnowledgeUseCase({
4146
}) => resolveCanonicalActiveKnowledgeDocumentContext(input, principal),
4247
async execute({ input, context, principal }) {
4348
const maxBytes = input.maxBytes ?? MAX_TEXT_EXTRACTION_BYTES
44-
if (!Number.isSafeInteger(maxBytes) || maxBytes < 1 || maxBytes > MAX_TEXT_EXTRACTION_BYTES)
49+
if (
50+
!Number.isSafeInteger(maxBytes) ||
51+
maxBytes < 1 ||
52+
maxBytes > MAX_KNOWLEDGE_DOCUMENT_FILE_SIZE
53+
)
4554
throw new OrchestrationError('validation', 'Invalid document read byte limit')
4655
input.signal?.throwIfAborted()
4756
const doc = context.document

‎bun.lock‎

Lines changed: 2 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎packages/sim-cli/package.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@
5959
"proper-lockfile": "4.1.2"
6060
},
6161
"devDependencies": {
62+
"@sim/testing": "workspace:*",
6263
"@sim/tsconfig": "workspace:*",
6364
"@sim/utils": "workspace:*",
6465
"@sim/workflow-code": "workspace:*",

‎packages/sim-cli/src/commands/protocol/logs-follow.test.ts‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,14 @@
1+
import { utilsHelpersMock, utilsHelpersMockFns } from '@sim/testing/mocks/utils-helpers.mock'
12
import { Command } from 'commander'
23
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
34
import type { ListLogsResponse } from '../../generated/v2-api'
45
import { SimApiError } from '../../http/client'
56
import { contextMockFns, contextMockState } from '../../test/context-mock'
67
import { attachLogsFollow, type LogRow } from './logs-follow'
78

8-
const { mockSleep } = vi.hoisted(() => ({
9-
mockSleep: vi.fn(() => Promise.resolve()),
10-
}))
9+
const { mockSleep } = utilsHelpersMockFns
1110

12-
vi.mock('@sim/utils/helpers', () => ({ sleep: mockSleep }))
11+
vi.mock('@sim/utils/helpers', () => utilsHelpersMock)
1312

1413
vi.mock('../../context', async () => (await import('../../test/context-mock')).contextMock)
1514

0 commit comments

Comments
 (0)