Skip to content
This repository was archived by the owner on Jun 26, 2026. It is now read-only.

Commit 9c95976

Browse files
committed
fix(forms): validate every SchemaForm-backed form before submit
The application deploy page and the five backup create/edit pages render SchemaForm with the submit button outside RJSF, so the Deploy/Create/Save handlers sent the spec to the API without ever running RJSF validation. A required field left empty — e.g. a disk row whose name was never picked — was submitted and silently produced an invalid or empty result. Expose a validate() handle on SchemaForm (delegating to RJSF's validateForm) and call it from every one of those submit handlers; an invalid form renders its errors inline and the submit is aborted. Assisted-By: Claude <noreply@anthropic.com> Signed-off-by: Aleksei Sviridkin <f@lex.la>
1 parent 8f983bf commit 9c95976

14 files changed

Lines changed: 641 additions & 16 deletions

‎apps/console/src/components/SchemaForm.test.tsx‎

Lines changed: 42 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
1+
import { createRef } from "react"
12
import { describe, it, expect } from "vitest"
2-
import { render, screen } from "@testing-library/react"
3-
import { SchemaForm } from "./SchemaForm.tsx"
3+
import { render, screen, act } from "@testing-library/react"
4+
import { SchemaForm, type SchemaFormHandle } from "./SchemaForm.tsx"
45
import { IMMUTABLE_HELP_TEXT } from "../lib/immutable-paths.ts"
56

67
const schema = JSON.stringify({
@@ -138,3 +139,42 @@ describe("SchemaForm immutableMode", () => {
138139
expect(screen.getByText(IMMUTABLE_HELP_TEXT)).toBeInTheDocument()
139140
})
140141
})
142+
143+
describe("SchemaForm validate handle", () => {
144+
const requiredSchema = JSON.stringify({
145+
type: "object",
146+
required: ["name"],
147+
properties: { name: { type: "string" }, note: { type: "string" } },
148+
})
149+
150+
function validate(ref: React.RefObject<SchemaFormHandle | null>): boolean | undefined {
151+
let result: boolean | undefined
152+
act(() => {
153+
result = ref.current?.validate()
154+
})
155+
return result
156+
}
157+
158+
it("reports invalid through the ref when a required field is missing", () => {
159+
const ref = createRef<SchemaFormHandle>()
160+
render(
161+
<SchemaForm ref={ref} openAPISchema={requiredSchema} formData={{}} onChange={noop} />,
162+
)
163+
164+
expect(validate(ref)).toBe(false)
165+
})
166+
167+
it("reports valid through the ref once the required field is populated", () => {
168+
const ref = createRef<SchemaFormHandle>()
169+
render(
170+
<SchemaForm
171+
ref={ref}
172+
openAPISchema={requiredSchema}
173+
formData={{ name: "demo-disk" }}
174+
onChange={noop}
175+
/>,
176+
)
177+
178+
expect(validate(ref)).toBe(true)
179+
})
180+
})

‎apps/console/src/components/SchemaForm.tsx‎

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { useMemo, useEffect, useRef } from "react"
1+
import { useMemo, useEffect, useRef, forwardRef, useImperativeHandle } from "react"
22
import Form from "@rjsf/core"
33
import validator from "@rjsf/validator-ajv8"
44
import { getDefaultFormState } from "@rjsf/utils"
@@ -267,14 +267,31 @@ interface SchemaFormProps {
267267
immutableMode?: "enforce" | "off"
268268
}
269269

270-
export function SchemaForm({
270+
export interface SchemaFormHandle {
271+
/**
272+
* Run RJSF validation against the current form data and render any errors
273+
* inline. Returns whether the form is valid. The Deploy button lives
274+
* outside this component and bypasses RJSF's own submit, so callers gate
275+
* their submit on this before sending the resource to the API.
276+
*/
277+
validate: () => boolean
278+
}
279+
280+
export const SchemaForm = forwardRef<SchemaFormHandle, SchemaFormProps>(function SchemaForm({
271281
openAPISchema,
272282
keysOrder,
273283
formData,
274284
onChange,
275285
children,
276286
immutableMode,
277-
}: SchemaFormProps) {
287+
}: SchemaFormProps, ref) {
288+
const formRef = useRef<Form>(null)
289+
useImperativeHandle(
290+
ref,
291+
() => ({ validate: () => formRef.current?.validateForm() ?? true }),
292+
[],
293+
)
294+
278295
// Parse the raw schema once, then derive the sanitised RJSFSchema and the
279296
// immutable-path set from it. We keep the raw object around so we don't
280297
// re-parse the same string twice on every render. The contract is "same
@@ -380,6 +397,7 @@ export function SchemaForm({
380397
return (
381398
<div className="rjsf-container">
382399
<Form
400+
ref={formRef}
383401
tagName="div"
384402
schema={schema}
385403
uiSchema={uiSchema}
@@ -396,4 +414,4 @@ export function SchemaForm({
396414
</Form>
397415
</div>
398416
)
399-
}
417+
})
Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
import { forwardRef, useImperativeHandle } from "react"
2+
import { describe, it, expect, vi, beforeEach } from "vitest"
3+
import { render, screen } from "@testing-library/react"
4+
import userEvent from "@testing-library/user-event"
5+
import { MemoryRouter } from "react-router"
6+
7+
// The Deploy button bypasses RJSF; in form mode the gate calls
8+
// SchemaForm.validate(), in YAML mode it is skipped. Mock SchemaForm so the
9+
// test drives that boolean directly, and YamlEditor so Monaco stays out.
10+
const h = vi.hoisted(() => ({
11+
validateReturn: true,
12+
createMutateAsync: vi.fn(),
13+
updateMutateAsync: vi.fn(),
14+
ad: {
15+
spec: {
16+
application: {
17+
kind: "VirtualMachine",
18+
plural: "virtualmachines",
19+
singular: "virtualmachine",
20+
openAPISchema: JSON.stringify({ type: "object", properties: {} }),
21+
},
22+
dashboard: {},
23+
},
24+
},
25+
}))
26+
27+
vi.mock("../lib/tenant-context.tsx", () => ({
28+
useTenantContext: () => ({ tenantNamespace: "tenant-test" }),
29+
}))
30+
vi.mock("../lib/app-definitions.ts", () => ({
31+
useApplicationDefinition: () => ({ data: h.ad, isLoading: false, error: null }),
32+
appDisplayName: () => "Virtual Machine",
33+
iconDataUrl: () => null,
34+
}))
35+
vi.mock("@cozystack/k8s-client", () => ({
36+
useK8sCreate: () => ({ mutateAsync: h.createMutateAsync, isPending: false }),
37+
useK8sUpdate: () => ({ mutateAsync: h.updateMutateAsync, isPending: false }),
38+
K8sApiError: class K8sApiError extends Error {},
39+
}))
40+
vi.mock("../components/SchemaForm.tsx", () => ({
41+
SchemaForm: forwardRef<{ validate: () => boolean }, Record<string, unknown>>(
42+
function MockSchemaForm(_props, ref) {
43+
useImperativeHandle(ref, () => ({ validate: () => h.validateReturn }))
44+
return null
45+
},
46+
),
47+
}))
48+
vi.mock("../components/YamlEditor.tsx", () => ({
49+
YamlEditor: ({ value }: { value: string }) => <textarea data-testid="yaml" readOnly value={value} />,
50+
}))
51+
52+
const { ApplicationOrderPage } = await import("./ApplicationOrderPage.tsx")
53+
54+
function renderPage() {
55+
return render(
56+
<MemoryRouter>
57+
<ApplicationOrderPage appNameOverride="virtualmachine" />
58+
</MemoryRouter>,
59+
)
60+
}
61+
62+
describe("ApplicationOrderPage submit validation gate", () => {
63+
beforeEach(() => {
64+
h.createMutateAsync.mockReset()
65+
h.createMutateAsync.mockResolvedValue({})
66+
h.updateMutateAsync.mockReset()
67+
h.updateMutateAsync.mockResolvedValue({})
68+
h.validateReturn = true
69+
})
70+
71+
it("does not POST in form mode when the form fails RJSF validation", async () => {
72+
h.validateReturn = false
73+
const user = userEvent.setup()
74+
renderPage()
75+
76+
await user.type(screen.getByRole("textbox"), "demo-vm")
77+
await user.click(screen.getByRole("button", { name: /^deploy$/i }))
78+
79+
expect(h.createMutateAsync).not.toHaveBeenCalled()
80+
})
81+
82+
it("POSTs in form mode when the form passes validation", async () => {
83+
h.validateReturn = true
84+
const user = userEvent.setup()
85+
renderPage()
86+
87+
await user.type(screen.getByRole("textbox"), "demo-vm")
88+
await user.click(screen.getByRole("button", { name: /^deploy$/i }))
89+
90+
expect(h.createMutateAsync).toHaveBeenCalledTimes(1)
91+
})
92+
93+
it("skips the gate in YAML mode even when validation would fail", async () => {
94+
// In YAML mode the spec is hand-authored, so the gate must not block it.
95+
h.validateReturn = false
96+
const user = userEvent.setup()
97+
renderPage()
98+
99+
await user.type(screen.getByRole("textbox"), "demo-vm")
100+
await user.click(screen.getByRole("button", { name: /yaml/i }))
101+
await user.click(screen.getByRole("button", { name: /^deploy$/i }))
102+
103+
expect(h.createMutateAsync).toHaveBeenCalledTimes(1)
104+
})
105+
})

‎apps/console/src/routes/ApplicationOrderPage.tsx‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ import {
1313
import { useTenantContext } from "../lib/tenant-context.tsx"
1414
import { composeResource } from "../lib/app-resource.ts"
1515
import { prepareUpdateSpec } from "../lib/prepare-update.ts"
16-
import { SchemaForm } from "../components/SchemaForm.tsx"
16+
import { SchemaForm, type SchemaFormHandle } from "../components/SchemaForm.tsx"
1717

1818
// Lazy-load the YAML editor so monaco and its workers are code-split into their
1919
// own chunk, fetched only when the YAML view is opened.
@@ -54,6 +54,7 @@ export function ApplicationOrderPage({
5454
// the value the user actually viewed.
5555
const initialSpecRef = useRef<unknown>(editMode?.initialSpec)
5656
const initialSpecCapturedRef = useRef(false)
57+
const schemaFormRef = useRef<SchemaFormHandle>(null)
5758
useEffect(() => {
5859
if (editMode && !initialSpecCapturedRef.current) {
5960
initialSpecCapturedRef.current = true
@@ -126,6 +127,13 @@ export function ApplicationOrderPage({
126127
alert("Please set a resource name.")
127128
return
128129
}
130+
// The Deploy button lives outside RJSF and bypasses its submit, so trigger
131+
// validation explicitly in form mode. RJSF renders the errors inline; abort
132+
// so an invalid spec (e.g. a disk row left without a name) is never sent to
133+
// the API. YAML mode hand-authors the spec and is left to the API to reject.
134+
if (mode === "form" && schemaFormRef.current && !schemaFormRef.current.validate()) {
135+
return
136+
}
129137
const body = composeResource(ad, tenantNamespace, snap.name, snap.spec)
130138
try {
131139
if (editMode) {
@@ -273,6 +281,7 @@ export function ApplicationOrderPage({
273281
{ad.spec?.application.openAPISchema && (
274282
<div className="rounded-lg border border-slate-200 bg-white p-4">
275283
<SchemaForm
284+
ref={schemaFormRef}
276285
openAPISchema={ad.spec.application.openAPISchema}
277286
keysOrder={ad.spec?.dashboard?.keysOrder}
278287
formData={spec}
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
import { forwardRef, useEffect, useImperativeHandle } from "react"
2+
import { describe, it, expect, vi, beforeEach } from "vitest"
3+
import { render, screen } from "@testing-library/react"
4+
import userEvent from "@testing-library/user-event"
5+
import { MemoryRouter } from "react-router"
6+
7+
// The submit button bypasses RJSF; the gate calls SchemaForm.validate(). Mock
8+
// SchemaForm so the test drives that boolean directly and emits a spec that
9+
// satisfies the page's own manual required-field checks, isolating the gate.
10+
const h = vi.hoisted(() => ({
11+
validateReturn: true,
12+
createMutateAsync: vi.fn(),
13+
validSpec: {
14+
applicationRef: { kind: "VirtualMachine", name: "demo" },
15+
strategyRef: { kind: "Strategy", name: "s3" },
16+
takenAt: "2024-01-01T00:00:00Z",
17+
},
18+
}))
19+
20+
vi.mock("../lib/tenant-context.tsx", () => ({
21+
useTenantContext: () => ({ tenantNamespace: "tenant-test" }),
22+
}))
23+
vi.mock("../lib/app-definitions.ts", () => ({
24+
useApplicationDefinitions: () => ({ data: { items: [] } }),
25+
}))
26+
vi.mock("../lib/use-crd-schema.ts", () => ({
27+
useCRDSchema: () => ({
28+
schema: JSON.stringify({ type: "object", properties: {} }),
29+
isLoading: false,
30+
}),
31+
}))
32+
vi.mock("@cozystack/k8s-client", () => ({
33+
useK8sCreate: () => ({ mutateAsync: h.createMutateAsync, isPending: false }),
34+
useK8sList: () => ({ data: undefined }),
35+
}))
36+
vi.mock("../components/SchemaForm.tsx", () => ({
37+
SchemaForm: forwardRef<{ validate: () => boolean }, { onChange: (d: unknown) => void }>(
38+
function MockSchemaForm({ onChange }, ref) {
39+
useImperativeHandle(ref, () => ({ validate: () => h.validateReturn }))
40+
useEffect(() => {
41+
onChange(h.validSpec)
42+
}, [onChange])
43+
return null
44+
},
45+
),
46+
}))
47+
48+
const { BackupCreatePage } = await import("./BackupCreatePage.tsx")
49+
50+
function renderPage() {
51+
return render(
52+
<MemoryRouter>
53+
<BackupCreatePage />
54+
</MemoryRouter>,
55+
)
56+
}
57+
58+
describe("BackupCreatePage submit validation gate", () => {
59+
beforeEach(() => {
60+
h.createMutateAsync.mockReset()
61+
h.createMutateAsync.mockResolvedValue({})
62+
h.validateReturn = true
63+
})
64+
65+
it("does not POST when the form fails RJSF validation", async () => {
66+
h.validateReturn = false
67+
const user = userEvent.setup()
68+
renderPage()
69+
70+
await user.type(screen.getByRole("textbox"), "my-backup")
71+
await user.click(screen.getByRole("button", { name: /create/i }))
72+
73+
expect(h.createMutateAsync).not.toHaveBeenCalled()
74+
})
75+
76+
it("POSTs when the form passes validation", async () => {
77+
h.validateReturn = true
78+
const user = userEvent.setup()
79+
renderPage()
80+
81+
await user.type(screen.getByRole("textbox"), "my-backup")
82+
await user.click(screen.getByRole("button", { name: /create/i }))
83+
84+
expect(h.createMutateAsync).toHaveBeenCalledTimes(1)
85+
})
86+
})

‎apps/console/src/routes/BackupCreatePage.tsx‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
1-
import { useState, useMemo } from "react"
1+
import { useState, useMemo, useRef } from "react"
22
import { useNavigate } from "react-router"
33
import { Archive, Save } from "lucide-react"
44
import { Button, Section, Spinner } from "@cozystack/ui"
55
import { useK8sCreate, useK8sList } from "@cozystack/k8s-client"
66
import { useTenantContext } from "../lib/tenant-context.tsx"
77
import { useApplicationDefinitions } from "../lib/app-definitions.ts"
88
import { useCRDSchema } from "../lib/use-crd-schema.ts"
9-
import { SchemaForm } from "../components/SchemaForm.tsx"
9+
import { SchemaForm, type SchemaFormHandle } from "../components/SchemaForm.tsx"
1010
import { enrichSchemaWithEnums } from "../lib/backup-utils.ts"
1111

1212
export function BackupCreatePage() {
@@ -15,6 +15,7 @@ export function BackupCreatePage() {
1515
const { data: appDefs } = useApplicationDefinitions()
1616
const [formData, setFormData] = useState<any>({})
1717
const [name, setName] = useState("")
18+
const schemaFormRef = useRef<SchemaFormHandle>(null)
1819

1920
// Get base schema from CRD
2021
const { schema: baseSchema, isLoading: schemaLoading } = useCRDSchema(
@@ -94,6 +95,10 @@ export function BackupCreatePage() {
9495
return
9596
}
9697

98+
// The submit button lives outside RJSF and bypasses its validation, so
99+
// trigger it explicitly; an invalid spec renders errors inline and aborts.
100+
if (schemaFormRef.current && !schemaFormRef.current.validate()) return
101+
97102
const resource = {
98103
apiVersion: "backups.cozystack.io/v1alpha1",
99104
kind: "Backup",
@@ -165,6 +170,7 @@ export function BackupCreatePage() {
165170

166171
<div>
167172
<SchemaForm
173+
ref={schemaFormRef}
168174
openAPISchema={schema}
169175
formData={formData}
170176
onChange={setFormData}

0 commit comments

Comments
 (0)