Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

fix(sql-review): validate required rule lists (#20558)

boojackc5cd4ad6a5c7
diff --git a/frontend/src/locales/sql-review/en-US.json b/frontend/src/locales/sql-review/en-US.json
index 3776b0065b..92e181d8b6 100644
--- a/frontend/src/locales/sql-review/en-US.json
+++ b/frontend/src/locales/sql-review/en-US.json
@@ -712,5 +712,9 @@
"bb-sql-review-prod-desc": "Comprehensive policy where you have total protection and best practices for your databases.",
"bb-sql-review-sample": "Sample Template",
"bb-sql-review-sample-desc": "A minimum template with DROP protection and disallow column nullable."
+ },
+ "validation": {
+ "rule-required": "Select at least one rule.",
+ "string-array-required": "Add at least one value for {{rule}}."
}
}
diff --git a/frontend/src/locales/sql-review/es-ES.json b/frontend/src/locales/sql-review/es-ES.json
index 775c54d95f..b1b6d06632 100644
--- a/frontend/src/locales/sql-review/es-ES.json
+++ b/frontend/src/locales/sql-review/es-ES.json
@@ -712,5 +712,9 @@
"bb-sql-review-prod-desc": "Política completa donde se tiene protección total y mejores prácticas para sus bases de datos.",
"bb-sql-review-sample": "Plantilla de Muestra",
"bb-sql-review-sample-desc": "Una plantilla mínima con protección de DROP y prohibición de columnas anulables."
+ },
+ "validation": {
+ "rule-required": "Seleccione al menos una regla.",
+ "string-array-required": "Agregue al menos un valor para {{rule}}."
}
}
diff --git a/frontend/src/locales/sql-review/ja-JP.json b/frontend/src/locales/sql-review/ja-JP.json
index 2d4cd6bfef..1eeacb00a6 100644
--- a/frontend/src/locales/sql-review/ja-JP.json
+++ b/frontend/src/locales/sql-review/ja-JP.json
@@ -712,5 +712,9 @@
"bb-sql-review-prod-desc": "データベースの総合的な保護とベストプラクティスを提供します。",
"bb-sql-review-sample": "サンプルテンプレート",
"bb-sql-review-sample-desc": "DROP保護とカラムのNULL許容を禁止した最小のテンプレート。"
+ },
+ "validation": {
+ "rule-required": "少なくとも 1 つのルールを選択してください。",
+ "string-array-required": "{{rule}} に少なくとも 1 つの値を追加してください。"
}
}
diff --git a/frontend/src/locales/sql-review/vi-VN.json b/frontend/src/locales/sql-review/vi-VN.json
index d184b8795b..ef3bd09b0b 100644
--- a/frontend/src/locales/sql-review/vi-VN.json
+++ b/frontend/src/locales/sql-review/vi-VN.json
@@ -712,5 +712,9 @@
"bb-sql-review-prod-desc": "Chính sách toàn diện, nơi bạn có sự bảo vệ và các phương pháp tốt nhất cho cơ sở dữ liệu.",
"bb-sql-review-sample": "Mẫu Ví dụ",
"bb-sql-review-sample-desc": "Một mẫu tối thiểu với bảo vệ DROP và không cho phép cột nullable."
+ },
+ "validation": {
+ "rule-required": "Chọn ít nhất một quy tắc.",
+ "string-array-required": "Thêm ít nhất một giá trị cho {{rule}}."
}
}
diff --git a/frontend/src/locales/sql-review/zh-CN.json b/frontend/src/locales/sql-review/zh-CN.json
index df33f753ee..cd5462c5e2 100644
--- a/frontend/src/locales/sql-review/zh-CN.json
+++ b/frontend/src/locales/sql-review/zh-CN.json
@@ -712,5 +712,9 @@
"bb-sql-review-prod-desc": "为您的数据库提供全面保护和最佳实践。",
"bb-sql-review-sample": "样例模版",
"bb-sql-review-sample-desc": "一个包括 DROP 保护和禁止列值为 NULL 的简易审核策略。"
+ },
+ "validation": {
+ "rule-required": "请选择至少一条规则。",
+ "string-array-required": "请为 {{rule}} 添加至少一个值。"
}
}
diff --git a/frontend/src/react/components/sql-review/Panels.test.tsx b/frontend/src/react/components/sql-review/Panels.test.tsx
new file mode 100644
index 0000000000..cecc15c12f
--- /dev/null
+++ b/frontend/src/react/components/sql-review/Panels.test.tsx
@@ -0,0 +1,181 @@
+import type { ReactElement } from "react";
+import { act } from "react";
+import { createRoot } from "react-dom/client";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+import { State } from "@/types/proto-es/v1/common_pb";
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+const mocks = vi.hoisted(() => ({
+ fetchProjectList: vi.fn(async () => ({ projects: [] })),
+ getReviewPolicyByResouce: vi.fn(),
+ removeResourceForReview: vi.fn(),
+ upsertReviewConfigTag: vi.fn(),
+}));
+
+let AttachResourcesPanel: typeof import("./Panels").AttachResourcesPanel;
+
+const appStoreState = {
+ environmentList: [],
+ fetchProjectList: mocks.fetchProjectList,
+ projectsByName: {},
+ serverInfo: { defaultProject: "projects/default" },
+};
+
+vi.mock("react-i18next", () => ({
+ initReactI18next: { type: "3rdParty", init: () => {} },
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+vi.mock("@/react/hooks/useEscapeKey", () => ({
+ useEscapeKey: vi.fn(),
+}));
+
+vi.mock("@/react/stores/app", () => ({
+ useAppStore: Object.assign(
+ (selector: (state: typeof appStoreState) => unknown) =>
+ selector(appStoreState),
+ {
+ getState: () => appStoreState,
+ }
+ ),
+}));
+
+vi.mock("@/react/stores/sqlReview", () => ({
+ useSQLReviewStore: () => ({
+ getReviewPolicyByResouce: mocks.getReviewPolicyByResouce,
+ removeResourceForReview: mocks.removeResourceForReview,
+ upsertReviewConfigTag: mocks.upsertReviewConfigTag,
+ }),
+}));
+
+vi.mock("@/utils", () => ({
+ hasWorkspacePermissionV2: vi.fn(() => true),
+}));
+
+vi.mock("@/react/components/ui/alert", () => ({
+ Alert: ({ description }: { description: React.ReactNode }) => (
+ <div>{description}</div>
+ ),
+}));
+
+vi.mock("@/react/components/ui/button", () => ({
+ Button: ({
+ children,
+ onClick,
+ }: {
+ children: React.ReactNode;
+ onClick?: () => void;
+ }) => <button onClick={onClick}>{children}</button>,
+}));
+
+vi.mock("@/react/components/ui/checkbox", () => ({
+ Checkbox: () => <input type="checkbox" readOnly />,
+}));
+
+vi.mock("@/react/components/ui/sheet", () => ({
+ Sheet: ({ children, open }: { children: React.ReactNode; open: boolean }) =>
+ open ? <div>{children}</div> : null,
+ SheetBody: ({ children }: { children: React.ReactNode }) => (
+ <div>{children}</div>
+ ),
+ SheetContent: ({ children }: { children: React.ReactNode }) => (
+ <div>{children}</div>
+ ),
+ SheetFooter: ({ children }: { children: React.ReactNode }) => (
+ <div>{children}</div>
+ ),
+ SheetHeader: ({ children }: { children: React.ReactNode }) => (
+ <div>{children}</div>
+ ),
+ SheetTitle: ({ children }: { children: React.ReactNode }) => (
+ <h2>{children}</h2>
+ ),
+}));
+
+const renderIntoContainer = (element: ReactElement) => {
+ const container = document.createElement("div");
+ const root = createRoot(container);
+
+ return {
+ container,
+ render: () =>
+ act(() => {
+ root.render(element);
+ }),
+ unmount: () =>
+ act(() => {
+ root.unmount();
+ }),
+ };
+};
+
+beforeEach(async () => {
+ vi.clearAllMocks();
+ appStoreState.projectsByName = {};
+ ({ AttachResourcesPanel } = await import("./Panels"));
+});
+
+describe("AttachResourcesPanel", () => {
+ test("prepares the project list in the app-store cache", () => {
+ const { render, unmount } = renderIntoContainer(
+ <AttachResourcesPanel
+ show
+ review={{
+ id: "reviewConfigs/test",
+ enforce: true,
+ name: "Test review",
+ resources: [],
+ ruleList: [],
+ }}
+ onClose={vi.fn()}
+ />
+ );
+
+ render();
+
+ expect(mocks.fetchProjectList).toHaveBeenCalledWith({
+ cache: true,
+ filter: { excludeDefault: true },
+ });
+
+ unmount();
+ });
+
+ test("does not render cached default project", () => {
+ appStoreState.projectsByName = {
+ "projects/default": {
+ name: "projects/default",
+ title: "Default project",
+ state: State.ACTIVE,
+ },
+ "projects/customer": {
+ name: "projects/customer",
+ title: "Customer project",
+ state: State.ACTIVE,
+ },
+ };
+ const { container, render, unmount } = renderIntoContainer(
+ <AttachResourcesPanel
+ show
+ review={{
+ id: "reviewConfigs/test",
+ enforce: true,
+ name: "Test review",
+ resources: [],
+ ruleList: [],
+ }}
+ onClose={vi.fn()}
+ />
+ );
+
+ render();
+
+ expect(container.textContent).toContain("Customer project");
+ expect(container.textContent).not.toContain("Default project");
+
+ unmount();
+ });
+});
diff --git a/frontend/src/react/components/sql-review/Panels.tsx b/frontend/src/react/components/sql-review/Panels.tsx
index 284977b10e..400ddd099c 100644
--- a/frontend/src/react/components/sql-review/Panels.tsx
+++ b/frontend/src/react/components/sql-review/Panels.tsx
@@ -156,21 +156,25 @@ export function AttachResourcesPanel({
const { t } = useTranslation();
const sqlReviewStore = useSQLReviewStore();
const projectsByName = useAppStore((s) => s.projectsByName);
+ const defaultProject = useAppStore((s) => s.serverInfo?.defaultProject ?? "");
const environments = useAppStore((s) => s.environmentList) ?? [];
const projects = useMemo(
() =>
Object.values(projectsByName).filter(
- (project) => project.state === State.ACTIVE
+ (project) =>
+ project.state === State.ACTIVE && project.name !== defaultProject
),
- [projectsByName]
+ [defaultProject, projectsByName]
);
const [resources, setResources] = useState<string[]>([]);
// Fetch projects on mount so the checkbox list is populated
useEffect(() => {
- useAppStore.getState().fetchProjectList({});
+ useAppStore
+ .getState()
+ .fetchProjectList({ cache: true, filter: { excludeDefault: true } });
}, []);
useEffect(() => {
diff --git a/frontend/src/react/components/sql-review/ReviewCreation.tsx b/frontend/src/react/components/sql-review/ReviewCreation.tsx
index 87b5beed22..bf8350ac23 100644
--- a/frontend/src/react/components/sql-review/ReviewCreation.tsx
+++ b/frontend/src/react/components/sql-review/ReviewCreation.tsx
@@ -6,7 +6,10 @@ import { useTranslation } from "react-i18next";
import { ResourceIdField } from "@/react/components/ResourceIdField";
import { Button } from "@/react/components/ui/button";
import { Input } from "@/react/components/ui/input";
-import { getTemplateId } from "@/react/lib/sql-review/utils";
+import {
+ getRuleMapValidationErrorTitle,
+ getTemplateId,
+} from "@/react/lib/sql-review/utils";
import { router } from "@/react/router";
import {
WORKSPACE_ROUTE_SQL_REVIEW,
@@ -28,6 +31,7 @@ import {
convertRuleMapToPolicyRuleList,
getRuleMapByEngine,
isBuiltinRule,
+ validateRuleMapByEngine,
withBuiltinRules,
} from "@/types";
import type { Engine } from "@/types/proto-es/v1/common_pb";
@@ -216,6 +220,16 @@ export function ReviewCreation({
return;
}
+ const validationError = validateRuleMapByEngine(ruleMapByEngine);
+ if (validationError) {
+ pushNotification({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: getRuleMapValidationErrorTitle(validationError),
+ });
+ return;
+ }
+
try {
const result = await store.upsertReviewPolicy({
title: policyName,
diff --git a/frontend/src/react/components/sql-review/RuleComponents.test.tsx b/frontend/src/react/components/sql-review/RuleComponents.test.tsx
new file mode 100644
index 0000000000..8283ac52f7
--- /dev/null
+++ b/frontend/src/react/components/sql-review/RuleComponents.test.tsx
@@ -0,0 +1,162 @@
+import type { ReactElement } from "react";
+import { act } from "react";
+import { createRoot } from "react-dom/client";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+import { Engine } from "@/types/proto-es/v1/common_pb";
+import {
+ SQLReviewRule_Level,
+ SQLReviewRule_Type,
+} from "@/types/proto-es/v1/review_config_service_pb";
+import type { RuleTemplateV2 } from "@/types/sqlReview";
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+let RuleEditDialog: typeof import("./RuleComponents").RuleEditDialog;
+
+vi.mock("react-i18next", () => ({
+ initReactI18next: { type: "3rdParty", init: () => {} },
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+vi.mock("@/react/i18n", () => ({
+ default: {
+ exists: vi.fn(() => false),
+ t: vi.fn((key: string) => key),
+ },
+}));
+
+vi.mock("@/react/components/ui/badge", () => ({
+ Badge: ({ children }: { children: React.ReactNode }) => (
+ <span>{children}</span>
+ ),
+}));
+
+vi.mock("@/react/components/ui/button", () => ({
+ Button: ({
+ children,
+ disabled,
+ onClick,
+ }: {
+ children: React.ReactNode;
+ disabled?: boolean;
+ onClick?: () => void;
+ }) => (
+ <button disabled={disabled} onClick={onClick}>
+ {children}
+ </button>
+ ),
+}));
+
+vi.mock("@/react/components/ui/checkbox", () => ({
+ Checkbox: () => <input type="checkbox" readOnly />,
+}));
+
+vi.mock("@/react/components/ui/dialog", () => ({
+ Dialog: ({ children }: { children: React.ReactNode }) => (
+ <div>{children}</div>
+ ),
+ DialogContent: ({ children }: { children: React.ReactNode }) => (
+ <div>{children}</div>
+ ),
+ DialogTitle: ({ children }: { children: React.ReactNode }) => (
+ <h2>{children}</h2>
+ ),
+}));
+
+vi.mock("@/react/components/ui/input", () => ({
+ Input: (props: React.InputHTMLAttributes<HTMLInputElement>) => (
+ <input {...props} />
+ ),
+}));
+
+vi.mock("@/react/components/ui/tooltip", () => ({
+ Tooltip: ({ children }: { children: React.ReactNode }) => (
+ <span>{children}</span>
+ ),
+}));
+
+const renderIntoContainer = (element: ReactElement) => {
+ const container = document.createElement("div");
+ const root = createRoot(container);
+
+ return {
+ container,
+ render: () =>
+ act(() => {
+ root.render(element);
+ }),
+ unmount: () =>
+ act(() => {
+ root.unmount();
+ }),
+ };
+};
+
+const tableDenyListRule = (list: string[]): RuleTemplateV2 => ({
+ type: SQLReviewRule_Type.TABLE_DISALLOW_DDL,
+ category: "TABLE",
+ engine: Engine.MYSQL,
+ level: SQLReviewRule_Level.ERROR,
+ componentList: [
+ {
+ key: "list",
+ payload: {
+ type: "STRING_ARRAY",
+ default: [],
+ value: list,
+ },
+ },
+ ],
+});
+
+beforeEach(async () => {
+ ({ RuleEditDialog } = await import("./RuleComponents"));
+});
+
+describe("RuleEditDialog", () => {
+ test("disables update for an empty required string-array payload", () => {
+ const { container, render, unmount } = renderIntoContainer(
+ <RuleEditDialog
+ rule={tableDenyListRule([])}
+ disabled={false}
+ onUpdateRule={vi.fn()}
+ onCancel={vi.fn()}
+ />
+ );
+
+ render();
+
+ const updateButton = [...container.querySelectorAll("button")].find(
+ (button) => button.textContent === "common.update"
+ );
+
+ expect(updateButton).toBeTruthy();
+ expect(updateButton).toBeDisabled();
+
+ unmount();
+ });
+
+ test("enables update for a configured required string-array payload", () => {
+ const { container, render, unmount } = renderIntoContainer(
+ <RuleEditDialog
+ rule={tableDenyListRule(["audit_log"])}
+ disabled={false}
+ onUpdateRule={vi.fn()}
+ onCancel={vi.fn()}
+ />
+ );
+
+ render();
+
+ const updateButton = [...container.querySelectorAll("button")].find(
+ (button) => button.textContent === "common.update"
+ );
+
+ expect(updateButton).toBeTruthy();
+ expect(updateButton).not.toBeDisabled();
+
+ unmount();
+ });
+});
diff --git a/frontend/src/react/components/sql-review/RuleComponents.tsx b/frontend/src/react/components/sql-review/RuleComponents.tsx
index cda5fe6b98..7a18382f65 100644
--- a/frontend/src/react/components/sql-review/RuleComponents.tsx
+++ b/frontend/src/react/components/sql-review/RuleComponents.tsx
@@ -1,5 +1,5 @@
import { CircleHelpIcon, XIcon } from "lucide-react";
-import { useEffect, useMemo, useRef, useState } from "react";
+import { useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { Badge } from "@/react/components/ui/badge";
import { Button } from "@/react/components/ui/button";
@@ -26,6 +26,7 @@ import {
getRuleLocalization,
getRuleLocalizationKey,
ruleTypeToString,
+ validateRuleMapByEngine,
} from "@/types/sqlReview";
// ---- Types ----
@@ -124,6 +125,7 @@ interface RuleConfigProps {
disabled: boolean;
size: "small" | "medium";
payloadRef?: React.MutableRefObject<PayloadValueType[]>;
+ onPayloadChange?: (payload: PayloadValueType[]) => void;
}
function configTitle(
@@ -147,6 +149,7 @@ export function RuleConfig({
disabled,
size,
payloadRef,
+ onPayloadChange,
}: RuleConfigProps) {
const [payload, setPayload] = useState<PayloadValueType[]>(() =>
getRulePayload(rule)
@@ -156,12 +159,13 @@ export function RuleConfig({
setPayload(getRulePayload(rule));
}, [rule.componentList]);
- // Expose payload to parent via ref
+ // Expose payload to parent consumers that need to validate or submit it.
useEffect(() => {
if (payloadRef) {
payloadRef.current = payload;
}
- }, [payload, payloadRef]);
+ onPayloadChange?.(payload);
+ }, [payload, payloadRef, onPayloadChange]);
const updatePayload = (index: number, value: PayloadValueType) => {
setPayload((prev) => {
@@ -373,17 +377,22 @@ export function RuleEditDialog({
}: RuleEditDialogProps) {
const { t } = useTranslation();
const [level, setLevel] = useState(rule.level);
- const payloadRef = useRef<PayloadValueType[]>(getRulePayload(rule));
+ const [payload, setPayload] = useState<PayloadValueType[]>(() =>
+ getRulePayload(rule)
+ );
const localization = useMemo(
() => getRuleLocalization(ruleTypeToString(rule.type), rule.engine),
[rule.type, rule.engine]
);
+ const componentList = useMemo(
+ () => payloadValueListToComponentList(rule, payload),
+ [rule, payload]
+ );
+ const validationError = validateRuleMapByEngine(
+ new Map([[rule.engine, new Map([[rule.type, { ...rule, componentList }]])]])
+ );
const handleConfirm = () => {
- const componentList = payloadValueListToComponentList(
- rule,
- payloadRef.current
- );
onUpdateRule({ level, componentList });
onCancel();
};
@@ -417,7 +426,7 @@ export function RuleEditDialog({
rule={rule}
disabled={disabled}
size="medium"
- payloadRef={payloadRef}
+ onPayloadChange={setPayload}
/>
)}
@@ -425,7 +434,10 @@ export function RuleEditDialog({
<Button variant="outline" onClick={onCancel}>
{t("common.cancel")}
</Button>
- <Button disabled={disabled} onClick={handleConfirm}>
+ <Button
+ disabled={disabled || !!validationError}
+ onClick={handleConfirm}
+ >
{t("common.update")}
</Button>
</div>
diff --git a/frontend/src/react/lib/sql-review/utils.ts b/frontend/src/react/lib/sql-review/utils.ts
index d8975a53f2..df0d1c85de 100644
--- a/frontend/src/react/lib/sql-review/utils.ts
+++ b/frontend/src/react/lib/sql-review/utils.ts
@@ -1,9 +1,16 @@
+import i18n from "@/react/i18n";
import type {
RuleConfigComponent,
+ RuleMapValidationError,
RuleTemplateV2,
SQLReviewPolicy,
} from "@/types";
-import { convertPolicyRuleToRuleTemplate, ruleTemplateMapV2 } from "@/types";
+import {
+ convertPolicyRuleToRuleTemplate,
+ getRuleLocalization,
+ ruleTemplateMapV2,
+ ruleTypeToString,
+} from "@/types";
import { SQLReviewRule_Type } from "@/types/proto-es/v1/review_config_service_pb";
import type { PayloadValueType } from "./rule-config-types";
@@ -87,3 +94,19 @@ export const payloadValueListToComponentList = (
[]
);
};
+
+export const getRuleMapValidationErrorTitle = (
+ error: RuleMapValidationError
+): string => {
+ if (error.type === "EMPTY_RULE_LIST") {
+ return i18n.t("sql-review.validation.rule-required");
+ }
+
+ const ruleTitle = getRuleLocalization(
+ ruleTypeToString(error.rule.type),
+ error.rule.engine
+ ).title;
+ return i18n.t("sql-review.validation.string-array-required", {
+ rule: ruleTitle,
+ });
+};
diff --git a/frontend/src/react/pages/settings/SQLReviewDetailPage.tsx b/frontend/src/react/pages/settings/SQLReviewDetailPage.tsx
index 9ddded6c29..5318679ba4 100644
--- a/frontend/src/react/pages/settings/SQLReviewDetailPage.tsx
+++ b/frontend/src/react/pages/settings/SQLReviewDetailPage.tsx
@@ -17,7 +17,10 @@ import {
DialogTitle,
} from "@/react/components/ui/dialog";
import { Input } from "@/react/components/ui/input";
-import { rulesToTemplate } from "@/react/lib/sql-review/utils";
+import {
+ getRuleMapValidationErrorTitle,
+ rulesToTemplate,
+} from "@/react/lib/sql-review/utils";
import { router } from "@/react/router";
import { WORKSPACE_ROUTE_SQL_REVIEW } from "@/react/router/handles";
import { useSQLReviewStore } from "@/react/stores/sqlReview";
@@ -28,6 +31,7 @@ import {
getRuleMapByEngine,
isBuiltinRule,
UNKNOWN_ID,
+ validateRuleMapByEngine,
withBuiltinRules,
} from "@/types";
import type { Engine } from "@/types/proto-es/v1/common_pb";
@@ -176,6 +180,16 @@ export function SQLReviewDetailPage({
}, [ruleListOfPolicy]);
const onApplyChanges = useCallback(async () => {
+ const validationError = validateRuleMapByEngine(ruleMapByEngine);
+ if (validationError) {
+ pushNotification({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: getRuleMapValidationErrorTitle(validationError),
+ });
+ return;
+ }
+
await store.upsertReviewPolicy({
id: reviewPolicy.id,
title: reviewPolicy.name,
diff --git a/frontend/src/types/sqlReview.test.ts b/frontend/src/types/sqlReview.test.ts
index 19b4cf92c7..19ae59ba4a 100644
--- a/frontend/src/types/sqlReview.test.ts
+++ b/frontend/src/types/sqlReview.test.ts
@@ -1,9 +1,18 @@
import { describe, expect, test } from "vitest";
-import { SQLReviewRule_Level } from "@/types/proto-es/v1/review_config_service_pb";
+import { Engine } from "@/types/proto-es/v1/common_pb";
+import {
+ SQLReviewRule_Level,
+ SQLReviewRule_Type,
+} from "@/types/proto-es/v1/review_config_service_pb";
import sqlReviewDevTemplate from "./sql-review.dev.yaml";
import sqlReviewProdTemplate from "./sql-review.prod.yaml";
import sqlReviewSampleTemplate from "./sql-review.sample.yaml";
import sqlReviewSchema from "./sql-review-schema.yaml";
+import {
+ convertRuleMapToPolicyRuleList,
+ type RuleTemplateV2,
+ validateRuleMapByEngine,
+} from "./sqlReview";
// Type for template rule data loaded from YAML
interface TemplateRule {
@@ -203,3 +212,90 @@ describe("SQL Review YAML Templates Validation", () => {
});
});
});
+
+describe("convertRuleMapToPolicyRuleList", () => {
+ const stringArrayRule = (
+ type: SQLReviewRule_Type,
+ list: string[]
+ ): RuleTemplateV2 => ({
+ type,
+ category: "TABLE",
+ engine: Engine.MYSQL,
+ level: SQLReviewRule_Level.ERROR,
+ componentList: [
+ {
+ key: "list",
+ payload: {
+ type: "STRING_ARRAY",
+ default: [],
+ value: list,
+ },
+ },
+ ],
+ });
+
+ const requiredStringArrayRuleTypes = [
+ SQLReviewRule_Type.COLUMN_REQUIRED,
+ SQLReviewRule_Type.COLUMN_TYPE_DISALLOW_LIST,
+ SQLReviewRule_Type.INDEX_PRIMARY_KEY_TYPE_ALLOWLIST,
+ SQLReviewRule_Type.INDEX_TYPE_ALLOW_LIST,
+ SQLReviewRule_Type.SYSTEM_CHARSET_ALLOWLIST,
+ SQLReviewRule_Type.SYSTEM_COLLATION_ALLOWLIST,
+ SQLReviewRule_Type.SYSTEM_FUNCTION_DISALLOWED_LIST,
+ SQLReviewRule_Type.TABLE_DISALLOW_DDL,
+ SQLReviewRule_Type.TABLE_DISALLOW_DML,
+ ];
+
+ test.each(
+ requiredStringArrayRuleTypes
+ )("reports empty string-array rule %s", (type) => {
+ const ruleMap = new Map([
+ [Engine.MYSQL, new Map([[type, stringArrayRule(type, [])]])],
+ ]);
+
+ expect(validateRuleMapByEngine(ruleMap)).toMatchObject({
+ type: "EMPTY_STRING_ARRAY",
+ rule: { type },
+ });
+ });
+
+ test("reports empty rule maps", () => {
+ expect(validateRuleMapByEngine(new Map())).toEqual({
+ type: "EMPTY_RULE_LIST",
+ });
+ });
+
+ test("keeps configured table DDL and DML deny-list rules valid", () => {
+ const ruleMap = new Map([
+ [
+ Engine.MYSQL,
+ new Map([
+ [
+ SQLReviewRule_Type.TABLE_DISALLOW_DDL,
+ stringArrayRule(SQLReviewRule_Type.TABLE_DISALLOW_DDL, [
+ "audit_log",
+ ]),
+ ],
+ [
+ SQLReviewRule_Type.TABLE_DISALLOW_DML,
+ stringArrayRule(SQLReviewRule_Type.TABLE_DISALLOW_DML, ["user"]),
+ ],
+ ]),
+ ],
+ ]);
+
+ expect(validateRuleMapByEngine(ruleMap)).toBeUndefined();
+
+ const rules = convertRuleMapToPolicyRuleList(ruleMap);
+ const getStringArrayList = (rule: (typeof rules)[number] | undefined) => {
+ expect(rule?.payload.case).toBe("stringArrayPayload");
+ return rule?.payload.case === "stringArrayPayload"
+ ? rule.payload.value.list
+ : [];
+ };
+
+ expect(rules).toHaveLength(2);
+ expect(getStringArrayList(rules[0])).toEqual(["audit_log"]);
+ expect(getStringArrayList(rules[1])).toEqual(["user"]);
+ });
+});
diff --git a/frontend/src/types/sqlReview.ts b/frontend/src/types/sqlReview.ts
index ab17815706..558a1b8bed 100644
--- a/frontend/src/types/sqlReview.ts
+++ b/frontend/src/types/sqlReview.ts
@@ -772,6 +772,58 @@ export const convertRuleMapToPolicyRuleList = (
return resp;
};
+export type RuleMapValidationError =
+ | { type: "EMPTY_RULE_LIST" }
+ | { type: "EMPTY_STRING_ARRAY"; rule: RuleTemplateV2 };
+
+const nonEmptyStringArrayRuleTypeList = new Set<SQLReviewRule_Type>([
+ SQLReviewRule_Type.COLUMN_REQUIRED,
+ SQLReviewRule_Type.COLUMN_TYPE_DISALLOW_LIST,
+ SQLReviewRule_Type.INDEX_PRIMARY_KEY_TYPE_ALLOWLIST,
+ SQLReviewRule_Type.INDEX_TYPE_ALLOW_LIST,
+ SQLReviewRule_Type.SYSTEM_CHARSET_ALLOWLIST,
+ SQLReviewRule_Type.SYSTEM_COLLATION_ALLOWLIST,
+ SQLReviewRule_Type.SYSTEM_FUNCTION_DISALLOWED_LIST,
+ SQLReviewRule_Type.TABLE_DISALLOW_DDL,
+ SQLReviewRule_Type.TABLE_DISALLOW_DML,
+]);
+
+export const validateRuleMapByEngine = (
+ ruleMapByEngine: Map<Engine, Map<SQLReviewRule_Type, RuleTemplateV2>>
+): RuleMapValidationError | undefined => {
+ let hasRule = false;
+
+ for (const mapByType of ruleMapByEngine.values()) {
+ for (const rule of mapByType.values()) {
+ hasRule = true;
+ if (hasEmptyRequiredStringArray(rule)) {
+ return { type: "EMPTY_STRING_ARRAY", rule };
+ }
+ }
+ }
+
+ if (!hasRule) {
+ return { type: "EMPTY_RULE_LIST" };
+ }
+
+ return undefined;
+};
+
+const hasEmptyRequiredStringArray = (rule: RuleTemplateV2): boolean => {
+ if (!nonEmptyStringArrayRuleTypeList.has(rule.type)) {
+ return false;
+ }
+
+ const stringArrayPayload = rule.componentList.find(
+ (c) => c.payload.type === "STRING_ARRAY"
+ )?.payload as StringArrayPayload | undefined;
+
+ return (
+ (stringArrayPayload?.value ?? stringArrayPayload?.default ?? []).length ===
+ 0
+ );
+};
+
// The convertRuleTemplateToPolicyRule will convert rule template to review policy rule for backend useage.
// Will throw exception if we don't implement the payload handler for specific type of rule.
const convertRuleTemplateToPolicyRule = (