Skip to content

armgit / dify

Public Imported from GitHub
0

Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.

fix(web): enforce schema depth limits through nested arrays (#44295)

Codadaabfa79a6c0a7
diff --git a/web/app/components/workflow/nodes/llm/components/json-schema-config-modal/__tests__/json-importer.spec.tsx b/web/app/components/workflow/nodes/llm/components/json-schema-config-modal/__tests__/json-importer.spec.tsx
index 65211def50d..bf505a6b88c 100644
--- a/web/app/components/workflow/nodes/llm/components/json-schema-config-modal/__tests__/json-importer.spec.tsx
+++ b/web/app/components/workflow/nodes/llm/components/json-schema-config-modal/__tests__/json-importer.spec.tsx
@@ -83,6 +83,56 @@ it('rejects objects exceeding the real depth limit and accepts a corrected objec
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
})
+it.each([1, 2])(
+ 'enforces the schema depth limit through %i consecutive arrays',
+ async (arrayCount) => {
+ const { user, onSubmit } = setup()
+ function exampleWithSchemaDepth(depth: number) {
+ let item: Record<string, unknown> = { leaf: 'value' }
+ // Count the root object, consecutive arrays and the first item object.
+ for (let level = arrayCount + 2; level < depth; level++) item = { nested: item }
+ let rows: unknown = item
+ for (let level = 0; level < arrayCount; level++) rows = [rows]
+ return { rows }
+ }
+ await user.click(importButton())
+ const input = screen.getByRole('textbox', { name: 'JSON input' })
+ await user.click(input)
+ await user.paste(JSON.stringify(exampleWithSchemaDepth(JSON_SCHEMA_MAX_DEPTH + 1)))
+ await user.click(submitButton())
+ expect(
+ screen.getByText(`Schema exceeds maximum depth of ${JSON_SCHEMA_MAX_DEPTH}.`),
+ ).toBeInTheDocument()
+ expect(onSubmit).not.toHaveBeenCalled()
+ expect(screen.getByRole('dialog')).toBeInTheDocument()
+
+ const boundaryExample = exampleWithSchemaDepth(JSON_SCHEMA_MAX_DEPTH)
+ await user.clear(input)
+ await user.paste(JSON.stringify(boundaryExample))
+ await user.click(submitButton())
+ expect(onSubmit).toHaveBeenCalledExactlyOnceWith(boundaryExample)
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
+ },
+)
+
+it('preserves empty arrays, primitive arrays and first-item schema inference', async () => {
+ const { user, onSubmit } = setup()
+ let laterItem: Record<string, unknown> = { leaf: 'value' }
+ for (let level = 0; level < JSON_SCHEMA_MAX_DEPTH; level++) laterItem = { nested: laterItem }
+ const example = {
+ empty: [],
+ primitives: [1, 2],
+ primitiveFirst: [1, laterItem],
+ objectFirst: [{ leaf: 'first' }, laterItem],
+ }
+ await user.click(importButton())
+ await user.click(screen.getByRole('textbox', { name: 'JSON input' }))
+ await user.paste(JSON.stringify(example))
+ await user.click(submitButton())
+ expect(onSubmit).toHaveBeenCalledExactlyOnceWith(example)
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
+})
+
it('reports malformed JSON and allows correction without replacing JSON.parse', async () => {
const { user, onSubmit } = setup()
await user.click(importButton())
diff --git a/web/app/components/workflow/nodes/llm/components/json-schema-config-modal/__tests__/json-schema-config.spec.tsx b/web/app/components/workflow/nodes/llm/components/json-schema-config-modal/__tests__/json-schema-config.spec.tsx
index 740a038a9b6..33272519e30 100644
--- a/web/app/components/workflow/nodes/llm/components/json-schema-config-modal/__tests__/json-schema-config.spec.tsx
+++ b/web/app/components/workflow/nodes/llm/components/json-schema-config-modal/__tests__/json-schema-config.spec.tsx
@@ -5,6 +5,7 @@ import userEvent from '@testing-library/user-event'
import { NuqsTestingAdapter } from 'nuqs/adapters/testing'
import { useState } from 'react'
import { ModelTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
+import { JSON_SCHEMA_MAX_DEPTH } from '@/config'
import { consoleQuery } from '@/service/console'
import { QueryClientTestProvider } from '@/test/console/query-provider'
import { createSystemFeaturesFixture } from '@/test/console/system-features'
@@ -203,6 +204,46 @@ describe('StructureOutput schema sessions', () => {
JSON.stringify(namedSchema, null, 2),
)
})
+ it.each(['save', 'switch to the visual editor'])(
+ 'checks consecutive-array depth before %s',
+ async (action) => {
+ const user = userEvent.setup()
+ const { onChange } = renderOutput()
+ function schemaWithDepth(depth: number) {
+ let item: object = emptySchema
+ // The root, two arrays and their object item contribute four levels.
+ for (let level = 4; level < depth; level++)
+ item = { ...emptySchema, properties: { nested: item } }
+ return {
+ ...emptySchema,
+ properties: { child: { type: 'array', items: { type: 'array', items: item } } },
+ }
+ }
+ await openEditor(user)
+ await editJSON(user, JSON.stringify(schemaWithDepth(JSON_SCHEMA_MAX_DEPTH + 1)))
+ await user.click(
+ action === 'save'
+ ? screen.getByRole('button', { name: saveName })
+ : screen.getByRole('tab', { name: 'Visual Editor' }),
+ )
+ expect(
+ screen.getByText(`Schema exceeds maximum depth of ${JSON_SCHEMA_MAX_DEPTH}.`),
+ ).toBeVisible()
+ expect(screen.getByRole('tab', { name: 'JSON Schema' })).toHaveAttribute(
+ 'aria-selected',
+ 'true',
+ )
+ expect(onChange).not.toHaveBeenCalled()
+
+ const boundarySchema = schemaWithDepth(JSON_SCHEMA_MAX_DEPTH)
+ await editJSON(user, JSON.stringify(boundarySchema))
+ await user.click(screen.getByRole('button', { name: saveName }))
+ await waitFor(() =>
+ expect(screen.queryByRole('dialog', { name: dialogName })).not.toBeInTheDocument(),
+ )
+ expect(onChange).toHaveBeenCalledExactlyOnceWith({ schema: boundarySchema })
+ },
+ )
it.each([
['invalid root', JSON.stringify({ type: 'string' })],
[
diff --git a/web/app/components/workflow/nodes/llm/utils.ts b/web/app/components/workflow/nodes/llm/utils.ts
index 87795bb7521..ef16840c10d 100644
--- a/web/app/components/workflow/nodes/llm/utils.ts
+++ b/web/app/components/workflow/nodes/llm/utils.ts
@@ -141,12 +141,12 @@ export const jsonToSchema = (json: any): Field => {
}
export const checkJsonDepth = (json: any) => {
- if (!json || getTypeOf(json) !== 'object') return 0
+ if (!json || typeof json !== 'object') return 0
let maxDepth = 0
if (getTypeOf(json) === 'array') {
- if (json[0] && getTypeOf(json[0]) === 'object') maxDepth = checkJsonDepth(json[0])
+ maxDepth = checkJsonDepth(json[0]) + 1
} else if (getTypeOf(json) === 'object') {
const propertyDepths = Object.values(json).map((value) => checkJsonDepth(value))
maxDepth = propertyDepths.length ? Math.max(...propertyDepths) + 1 : 1
@@ -165,8 +165,8 @@ export const checkJsonSchemaDepth = (schema: Field) => {
checkJsonSchemaDepth(value),
)
maxDepth = propertyDepths.length ? Math.max(...propertyDepths) + 1 : 1
- } else if (schema.type === Type.array && schema.items && schema.items.type === Type.object) {
- maxDepth = checkJsonSchemaDepth(schema.items) + 1
+ } else if (schema.type === Type.array) {
+ maxDepth = (schema.items ? checkJsonSchemaDepth(schema.items) : 0) + 1
}
return maxDepth