Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
fix(review): tell a missing policy row from a failed or unenforced read
rebelicefe10b238eb08
diff --git a/frontend/src/components/sql-review/standardRules.test.ts b/frontend/src/components/sql-review/standardRules.test.tsindex e1f41e21dc..aa7f9d9619 100644--- a/frontend/src/components/sql-review/standardRules.test.ts+++ b/frontend/src/components/sql-review/standardRules.test.ts@@ -8,12 +8,14 @@ import {} from "@/types/proto-es/v1/org_policy_service_pb";import { ReviewRuleType } from "@/types/proto-es/v1/review_rule_pb";import {+ effectiveWorkspaceRules,isStandardReviewOn,reviewRulesOfPolicy,STANDARD_RULE_TYPES,sameStandardRules,sortStandardRules,standardRuleText,+ storedReviewRules,} from "./standardRules";const t = ((key: string) => key) as unknown as TFunction;@@ -61,43 +63,53 @@ describe("standard rules", () => {).toBe(false);});+ const policy = (enforce: boolean, rules: ReviewRuleType[]) =>+ create(PolicySchema, {+ type: PolicyType.REVIEW_RULE,+ enforce,+ policy: {+ case: "reviewRulePolicy",+ value: create(ReviewRulePolicySchema, { rules }),+ },+ });+ // What the store caches when a project has no policy of its own.+ const noPolicy = create(PolicySchema, {+ name: "projects/p/policies/review_rule",+ });+ const switchedOff = policy(false, [ReviewRuleType.SYNTAX]);+ const customized = policy(true, [+ ReviewRuleType.DISALLOW_RENAME,+ ReviewRuleType.SYNTAX,+ ]);+test("read the rules of a policy, and nothing from a policy without one", () => {expect(reviewRulesOfPolicy(undefined)).toBeUndefined();// Switched off through the API: the backend reads it as absent.- expect(- reviewRulesOfPolicy(- create(PolicySchema, {- type: PolicyType.REVIEW_RULE,- enforce: false,- policy: {- case: "reviewRulePolicy",- value: create(ReviewRulePolicySchema, {- rules: [ReviewRuleType.SYNTAX],- }),- },- })- )- ).toBeUndefined();- // What the store caches when a project has no policy of its own.- expect(- reviewRulesOfPolicy(- create(PolicySchema, { name: "projects/p/policies/review_rule" })- )- ).toBeUndefined();- expect(- reviewRulesOfPolicy(- create(PolicySchema, {- type: PolicyType.REVIEW_RULE,- enforce: true,- policy: {- case: "reviewRulePolicy",- value: create(ReviewRulePolicySchema, {- rules: [ReviewRuleType.DISALLOW_RENAME, ReviewRuleType.SYNTAX],- }),- },- })- )- ).toEqual([ReviewRuleType.SYNTAX, ReviewRuleType.DISALLOW_RENAME]);+ expect(reviewRulesOfPolicy(switchedOff)).toBeUndefined();+ expect(reviewRulesOfPolicy(noPolicy)).toBeUndefined();+ expect(reviewRulesOfPolicy(customized)).toEqual([+ ReviewRuleType.SYNTAX,+ ReviewRuleType.DISALLOW_RENAME,+ ]);+ });++ test("read the stored rules of a row whether or not it is enforced", () => {+ expect(storedReviewRules(undefined)).toBeUndefined();+ expect(storedReviewRules(noPolicy)).toBeUndefined();+ expect(storedReviewRules(switchedOff)).toEqual([ReviewRuleType.SYNTAX]);+ expect(storedReviewRules(customized)).toEqual([+ ReviewRuleType.SYNTAX,+ ReviewRuleType.DISALLOW_RENAME,+ ]);+ });++ test("apply every rule for a workspace without an enforced policy", () => {+ expect(effectiveWorkspaceRules(undefined)).toBeUndefined();+ expect(effectiveWorkspaceRules(switchedOff)).toEqual(STANDARD_RULE_TYPES);+ expect(effectiveWorkspaceRules(customized)).toEqual([+ ReviewRuleType.SYNTAX,+ ReviewRuleType.DISALLOW_RENAME,+ ]);});test("need SYNTAX for standard review to run", () => {diff --git a/frontend/src/components/sql-review/standardRules.ts b/frontend/src/components/sql-review/standardRules.tsindex 826ee2c6d6..7723e48429 100644--- a/frontend/src/components/sql-review/standardRules.ts+++ b/frontend/src/components/sql-review/standardRules.ts@@ -35,15 +35,31 @@ export const sameStandardRules = ();};+// The rules a resource's own policy row lists, whatever its enforce flag;+// undefined when the resource has no row.+export const storedReviewRules = (+ policy: Policy | undefined+): ReviewRuleType[] | undefined =>+ policy?.policy.case === "reviewRulePolicy"+ ? sortStandardRules(policy.policy.value.rules)+ : undefined;+// The rules a cached review rule policy switches on, or undefined when the// resource has none of its own. A policy that is not enforced counts as// absent, as the backend reads it.export const reviewRulesOfPolicy = (policy: Policy | undefined): ReviewRuleType[] | undefined =>- policy?.policy.case === "reviewRulePolicy" && policy.enforce- ? sortStandardRules(policy.policy.value.rules)- : undefined;+ policy?.enforce ? storedReviewRules(policy) : undefined;++// The rules the backend applies for the workspace: its enforced policy, else+// every rule. Undefined when the policy could not be read.+export const effectiveWorkspaceRules = (+ policy: Policy | undefined+): ReviewRuleType[] | undefined =>+ policy === undefined+ ? undefined+ : (reviewRulesOfPolicy(policy) ?? [...STANDARD_RULE_TYPES]);// SYNTAX gates the rest: without it no standard rule runs.export const isStandardReviewOn = (rules: readonly ReviewRuleType[]): boolean =>diff --git a/frontend/src/locales/sql-review/en-US.json b/frontend/src/locales/sql-review/en-US.jsonindex dcfade31e0..5f03fd3c81 100644--- a/frontend/src/locales/sql-review/en-US.json+++ b/frontend/src/locales/sql-review/en-US.json@@ -736,9 +736,11 @@"view-workspace-rules": "View workspace rules"},"description": "Built-in rules that review the SQL of every issue. Projects that do not customize their rules follow these.",+ "load-failed": "The standard rules could not be loaded.","off": "Off","on": "On","project-description": "Built-in rules that review the SQL of every issue in this project.",+ "retry": "Retry","rule": {"disallow-drop-constraint": {"description": "Flags dropping a PRIMARY KEY, FOREIGN KEY, UNIQUE, or CHECK constraint.",diff --git a/frontend/src/locales/sql-review/es-ES.json b/frontend/src/locales/sql-review/es-ES.jsonindex 5cad0aa4f6..f0c568b1b3 100644--- a/frontend/src/locales/sql-review/es-ES.json+++ b/frontend/src/locales/sql-review/es-ES.json@@ -736,9 +736,11 @@"view-workspace-rules": "Ver las reglas del espacio de trabajo"},"description": "Reglas integradas que revisan el SQL de cada issue. Los proyectos que no personalizan sus reglas siguen estas.",+ "load-failed": "No se pudieron cargar las reglas estándar.","off": "Desactivada","on": "Activada","project-description": "Reglas integradas que revisan el SQL de cada issue de este proyecto.",+ "retry": "Reintentar","rule": {"disallow-drop-constraint": {"description": "Señala la eliminación de una restricción PRIMARY KEY, FOREIGN KEY, UNIQUE o CHECK.",diff --git a/frontend/src/locales/sql-review/ja-JP.json b/frontend/src/locales/sql-review/ja-JP.jsonindex 584c328126..224a313625 100644--- a/frontend/src/locales/sql-review/ja-JP.json+++ b/frontend/src/locales/sql-review/ja-JP.json@@ -736,9 +736,11 @@"view-workspace-rules": "ワークスペースのルールを表示"},"description": "すべての Issue の SQL をレビューする組み込みルールです。ルールをカスタマイズしていないプロジェクトはこの設定に従います。",+ "load-failed": "標準ルールを読み込めませんでした。","off": "オフ","on": "オン","project-description": "このプロジェクトのすべての Issue の SQL をレビューする組み込みルールです。",+ "retry": "再試行","rule": {"disallow-drop-constraint": {"description": "PRIMARY KEY、FOREIGN KEY、UNIQUE、CHECK 制約の削除を検出します。",diff --git a/frontend/src/locales/sql-review/vi-VN.json b/frontend/src/locales/sql-review/vi-VN.jsonindex 26abd987b8..e39c7c834c 100644--- a/frontend/src/locales/sql-review/vi-VN.json+++ b/frontend/src/locales/sql-review/vi-VN.json@@ -736,9 +736,11 @@"view-workspace-rules": "Xem quy tắc của không gian làm việc"},"description": "Các quy tắc tích hợp sẵn dùng để đánh giá SQL của mọi issue. Các dự án không tùy chỉnh quy tắc sẽ tuân theo các quy tắc này.",+ "load-failed": "Không thể tải các quy tắc tiêu chuẩn.","off": "Tắt","on": "Bật","project-description": "Các quy tắc tích hợp sẵn dùng để đánh giá SQL của mọi issue trong dự án này.",+ "retry": "Thử lại","rule": {"disallow-drop-constraint": {"description": "Đánh dấu việc xóa ràng buộc PRIMARY KEY, FOREIGN KEY, UNIQUE hoặc CHECK.",diff --git a/frontend/src/locales/sql-review/zh-CN.json b/frontend/src/locales/sql-review/zh-CN.jsonindex 80f96bb449..cd73be10c8 100644--- a/frontend/src/locales/sql-review/zh-CN.json+++ b/frontend/src/locales/sql-review/zh-CN.json@@ -736,9 +736,11 @@"view-workspace-rules": "查看工作空间规则"},"description": "内置规则,审核每个工单中的 SQL。未自定义规则的项目遵循这里的设置。",+ "load-failed": "标准规则加载失败。","off": "关","on": "开","project-description": "内置规则,审核此项目每个工单中的 SQL。",+ "retry": "重试","rule": {"disallow-drop-constraint": {"description": "标记删除 PRIMARY KEY、FOREIGN KEY、UNIQUE 或 CHECK 约束的操作。",diff --git a/frontend/src/routes/project/ProjectSQLReviewPage.test.tsx b/frontend/src/routes/project/ProjectSQLReviewPage.test.tsxindex 9f1ffcea5c..cc57f16760 100644--- a/frontend/src/routes/project/ProjectSQLReviewPage.test.tsx+++ b/frontend/src/routes/project/ProjectSQLReviewPage.test.tsx@@ -16,6 +16,8 @@ const PROJECT = "projects/p";const mocks = vi.hoisted(() => ({permissions: {} as Record<string, boolean>,+ // Parents whose read fails: the store then caches nothing for them.+ unreadable: new Set<string>(),upsertPolicy: vi.fn(),deletePolicy: vi.fn(),fetchPolicy: vi.fn(),@@ -83,6 +85,7 @@ vi.mock("@/stores/app", async () => {getPolicyByParentAndType: ({ parentPath }) => get().policies[parentPath],getOrFetchPolicyByParentAndType: async (params) => {mocks.fetchPolicy(params);+ if (mocks.unreadable.has(params.parentPath)) return undefined;if (!get().policies[params.parentPath]) {set((state) => ({policies: {@@ -130,11 +133,15 @@ const seedPolicies = (policies: Record<string, Policy>) =>).setState({ policies });const { ProjectSQLReviewPage } = await import("./ProjectSQLReviewPage");-const reviewRulePolicy = (parent: string, rules: ReviewRuleType[]): Policy =>+const reviewRulePolicy = (+ parent: string,+ rules: ReviewRuleType[],+ enforce = true+): Policy =>create(PolicySchema, {name: `${parent}/policies/review_rule`,type: PolicyType.REVIEW_RULE,- enforce: true,+ enforce,policy: {case: "reviewRulePolicy",value: create(ReviewRulePolicySchema, { rules }),@@ -176,6 +183,7 @@ const update = () =>describe("ProjectSQLReviewPage", () => {beforeEach(() => {mocks.permissions = {};+ mocks.unreadable.clear();mocks.upsertPolicy.mockReset();mocks.deletePolicy.mockReset();mocks.fetchPolicy.mockReset();@@ -299,6 +307,79 @@ describe("ProjectSQLReviewPage", () => {expect(ruleSwitch("require-where")).not.toHaveAttribute("data-disabled");});+ test("a workspace policy switched off through the API counts as every rule", async () => {+ seedPolicies({+ [WORKSPACE]: reviewRulePolicy(WORKSPACE, [ReviewRuleType.SYNTAX], false),+ });+ const customize = await renderLoaded();++ expect(customize).toHaveAttribute("aria-checked", "false");+ expect(screen.getAllByText("sql-review.standard-rules.on")).toHaveLength(+ 11+ );+ fireEvent.click(customize);+ expect(ruleSwitch("disallow-truncate")).toHaveAttribute(+ "aria-checked",+ "true"+ );+ });++ test("a project row switched off through the API is updated, not created", async () => {+ mocks.permissions = { "bb.policies.create": false };+ seedPolicies({+ [WORKSPACE]: workspacePolicy(),+ [PROJECT]: reviewRulePolicy(PROJECT, [ReviewRuleType.SYNTAX], false),+ });+ const customize = await renderLoaded();++ // The row is not in force, so the project follows the workspace.+ expect(customize).toHaveAttribute("aria-checked", "false");+ expect(customize).not.toHaveAttribute("data-disabled");+ fireEvent.click(customize);+ expect(ruleSwitch("require-where")).not.toHaveAttribute("data-disabled");+ await update();++ expect(mocks.upsertPolicy).toHaveBeenCalledTimes(1);+ expect(mocks.upsertPolicy.mock.calls[0][0].policy.enforce).toBe(true);+ });++ test("a project row switched off through the API needs bb.policies.update", async () => {+ mocks.permissions = { "bb.policies.update": false };+ seedPolicies({+ [WORKSPACE]: workspacePolicy(),+ [PROJECT]: reviewRulePolicy(PROJECT, [ReviewRuleType.SYNTAX], false),+ });+ const customize = await renderLoaded();++ expect(customize).toHaveAttribute("data-disabled");+ });++ test("a failed read shows an error instead of the switches, and retry reads again", async () => {+ mocks.unreadable.add(PROJECT);+ render(<ProjectSQLReviewPage projectId="p" />);++ expect(await screen.findByRole("alert")).toHaveTextContent(+ "sql-review.standard-rules.load-failed"+ );+ expect(screen.queryAllByRole("switch")).toHaveLength(0);++ mocks.unreadable.clear();+ fireEvent.click(+ screen.getByRole("button", { name: "sql-review.standard-rules.retry" })+ );++ const customize = await screen.findByRole("switch", {+ name: "sql-review.standard-rules.customize.self",+ });+ expect(customize).toHaveAttribute("aria-checked", "false");+ expect(screen.queryByRole("alert")).not.toBeInTheDocument();+ expect(mocks.fetchPolicy).toHaveBeenCalledWith({+ parentPath: PROJECT,+ policyType: PolicyType.REVIEW_RULE,+ refresh: true,+ });+ });+test("undoing an unsaved switch needs no permission", async () => {mocks.permissions = { "bb.policies.delete": false };const customize = await renderLoaded();diff --git a/frontend/src/routes/project/ProjectSQLReviewPage.tsx b/frontend/src/routes/project/ProjectSQLReviewPage.tsxindex 91cbefe509..5907e614fd 100644--- a/frontend/src/routes/project/ProjectSQLReviewPage.tsx+++ b/frontend/src/routes/project/ProjectSQLReviewPage.tsx@@ -7,10 +7,13 @@ import { RouterLink } from "@/components/RouterLink";import { StandardRuleSwitches } from "@/components/sql-review/StandardRuleSwitches";import { SwitchRow } from "@/components/sql-review/SwitchRow";import {+ effectiveWorkspaceRules,reviewRulesOfPolicy,STANDARD_RULE_TYPES,sameStandardRules,+ storedReviewRules,} from "@/components/sql-review/standardRules";+import { Alert } from "@/components/ui/alert";import { Button } from "@/components/ui/button";import { StickyActionFooter } from "@/components/ui/sticky-action-footer";import { useWorkspaceResourceName } from "@/hooks/useAppState";@@ -32,12 +35,17 @@ import { hasProjectPermissionV2, hasWorkspacePermissionV2 } from "@/utils";interface ProjectStandardRules {// False until both the project and the workspace policy have been read.loaded: boolean;+ readFailed: boolean;+ reload: () => void;// Whether the project has rules of its own; otherwise it follows the// workspace.customized: boolean;setCustomized: (customized: boolean) => void;// Whether the stored policy is the project's own; the draft may differ.storedCustomized: boolean;+ // Whether the project has a policy row at all. A row switched off through+ // the API is not customized, yet a save updates it rather than creating.+ hasOwnRow: boolean;// The rules in force: the project's own while customized, else the// workspace's. Undefined when the workspace policy could not be read.rules: ReviewRuleType[] | undefined;@@ -70,27 +78,43 @@ export function useProjectStandardRules(policyType: PolicyType.REVIEW_RULE,}));+ const [attempt, setAttempt] = useState(0);const [loaded, setLoaded] = useState(false);+ const [readFailed, setReadFailed] = useState(false);useEffect(() => {if (!workspace) return;+ let active = true;setLoaded(false);+ setReadFailed(false);const store = useAppStore.getState();- void Promise.all([- store.getOrFetchPolicyByParentAndType({- parentPath: projectName,- policyType: PolicyType.REVIEW_RULE,- }),- store.getOrFetchPolicyByParentAndType({- parentPath: workspace,- policyType: PolicyType.REVIEW_RULE,- }),- ]).then(() => setLoaded(true));- }, [projectName, workspace]);+ const finds = [projectName, workspace].map((parentPath) => ({+ parentPath,+ policyType: PolicyType.REVIEW_RULE,+ }));+ void Promise.all(+ finds.map((find) =>+ store.getOrFetchPolicyByParentAndType({ ...find, refresh: attempt > 0 })+ )+ ).then(() => {+ if (!active) return;+ // A read that failed leaves nothing in the cache, where a project+ // without its own policy leaves a policy with no payload.+ if (+ finds.some((find) => store.getPolicyByParentAndType(find) === undefined)+ ) {+ setReadFailed(true);+ return;+ }+ setLoaded(true);+ });+ return () => {+ active = false;+ };+ }, [projectName, workspace, attempt]);- // A project without its own policy reads as NotFound, which the store- // caches as a policy with no payload.const storedRules = reviewRulesOfPolicy(projectPolicy);- const workspaceRules = reviewRulesOfPolicy(workspacePolicy);+ const hasOwnRow = storedReviewRules(projectPolicy) !== undefined;+ const workspaceRules = effectiveWorkspaceRules(workspacePolicy);const storedCustomized = storedRules !== undefined;const [draft, setDraft] = useState<Draft>();@@ -152,9 +176,12 @@ export function useProjectStandardRules(return {loaded,+ readFailed,+ reload: () => setAttempt((n) => n + 1),customized,setCustomized,storedCustomized,+ hasOwnRow,rules: customized ? ownRules : workspaceRules,setRules: (rules) => setDraft({ customized: true, rules }),isDirty,@@ -177,17 +204,16 @@ export function ProjectSQLReviewPage({ projectId }: { projectId: string }) {const can = (permission: Permission) =>hasProjectPermissionV2(project, permission);- const canCreate = can("bb.policies.create");- const canUpdate = can("bb.policies.update");- const canDelete = can("bb.policies.delete");- // Switching customization on creates the project policy and switching it- // off deletes it; undoing an unsaved switch does neither.+ // Switching customization on and editing the project's own rules save the+ // project policy: a create when the project has no row, else an update.+ // Switching customization off deletes the row. Undoing an unsaved switch+ // does neither.+ const canSave = standardRules.hasOwnRow+ ? can("bb.policies.update")+ : can("bb.policies.create");const customizeLocked = standardRules.customized- ? standardRules.storedCustomized && !canDelete- : !standardRules.storedCustomized && !canCreate;- // The rules save as a create while the project still follows the- // workspace, and as an update once it has a policy of its own.- const rulesLocked = standardRules.storedCustomized ? !canUpdate : !canCreate;+ ? standardRules.storedCustomized && !can("bb.policies.delete")+ : !standardRules.storedCustomized && !canSave;const canViewWorkspaceRules =hasWorkspacePermissionV2("bb.reviewConfigs.list") &&hasWorkspacePermissionV2("bb.policies.get");@@ -203,6 +229,21 @@ export function ProjectSQLReviewPage({ projectId }: { projectId: string }) {{t("sql-review.standard-rules.project-description")}</p></div>+ {standardRules.readFailed && (+ <Alert+ variant="error"+ description={t("sql-review.standard-rules.load-failed")}+ >+ <Button+ className="mt-3"+ appearance="outline"+ size="sm"+ onClick={standardRules.reload}+ >+ {t("sql-review.standard-rules.retry")}+ </Button>+ </Alert>+ )}{standardRules.loaded && (<><SwitchRow@@ -234,7 +275,7 @@ export function ProjectSQLReviewPage({ projectId }: { projectId: string }) {<StandardRuleSwitchesrules={standardRules.rules}onChange={standardRules.setRules}- disabled={rulesLocked || standardRules.saving}+ disabled={!canSave || standardRules.saving}readOnly={!standardRules.customized}/>)}diff --git a/frontend/src/routes/workspace/SQLReviewStandardRulesSection.test.tsx b/frontend/src/routes/workspace/SQLReviewStandardRulesSection.test.tsxindex 34ebf30db6..218ba88e55 100644--- a/frontend/src/routes/workspace/SQLReviewStandardRulesSection.test.tsx+++ b/frontend/src/routes/workspace/SQLReviewStandardRulesSection.test.tsx@@ -15,6 +15,8 @@ const WORKSPACE = "workspaces/ws";const mocks = vi.hoisted(() => ({permissions: {} as Record<string, boolean>,+ fetchPolicy: vi.fn(),+ listPolicies: vi.fn(),upsertPolicy: vi.fn(),pushNotification: vi.fn(),}));@@ -44,7 +46,12 @@ vi.mock("@/stores/app", async () => {}) => StorePolicy | undefined;getOrFetchPolicyByParentAndType: (params: {parentPath: string;+ refresh?: boolean;}) => Promise<StorePolicy | undefined>;+ listPolicies: (params: {+ parentPath: string;+ showDeleted?: boolean;+ }) => Promise<StorePolicy[]>;upsertPolicy: (params: {parentPath: string;policy: Partial<StorePolicy>;@@ -52,8 +59,12 @@ vi.mock("@/stores/app", async () => {}>()((set, get) => ({policies: {},getPolicyByParentAndType: ({ parentPath }) => get().policies[parentPath],- getOrFetchPolicyByParentAndType: async ({ parentPath }) =>- get().policies[parentPath],+ // A failed read caches nothing, as the real store does.+ getOrFetchPolicyByParentAndType: async (params) => {+ mocks.fetchPolicy(params);+ return get().policies[params.parentPath];+ },+ listPolicies: async (params) => mocks.listPolicies(params),upsertPolicy: async (params) => {await mocks.upsertPolicy(params);const saved = params.policy as StorePolicy;@@ -77,17 +88,25 @@ const seedPolicies = (policies: Record<string, Policy>) =>const { SQLReviewStandardRulesSection, useWorkspaceStandardRules } =await import("./SQLReviewStandardRulesSection");-const reviewRulePolicy = (rules: ReviewRuleType[]): Policy =>+const reviewRulePolicy = (+ rules: ReviewRuleType[],+ enforce = true+): Policy =>create(PolicySchema, {name: `${WORKSPACE}/policies/review_rule`,type: PolicyType.REVIEW_RULE,- enforce: true,+ enforce,policy: {case: "reviewRulePolicy",value: create(ReviewRulePolicySchema, { rules }),},});+const seedWorkspaceRow = (policy: Policy | null) => {+ seedPolicies(policy ? { [WORKSPACE]: policy } : {});+ mocks.listPolicies.mockResolvedValue(policy ? [policy] : []);+};+function Harness() {const standardRules = useWorkspaceStandardRules(true);return (@@ -109,16 +128,23 @@ const ruleSwitch = (rule: string) =>name: `sql-review.standard-rules.rule.${rule}.title`,});+const everySwitch = () => screen.getAllByRole("switch");++const findSwitches = () => screen.findAllByRole("switch");+describe("SQLReviewStandardRulesSection", () => {beforeEach(() => {mocks.permissions = {};+ mocks.fetchPolicy.mockReset();+ mocks.listPolicies.mockReset();mocks.upsertPolicy.mockReset();mocks.pushNotification.mockReset();- seedPolicies({ [WORKSPACE]: reviewRulePolicy([...STANDARD_RULE_TYPES]) });+ seedWorkspaceRow(reviewRulePolicy([...STANDARD_RULE_TYPES]));});test("saves the edited rules as the enforced workspace policy", async () => {render(<Harness />);+ await findSwitches();expect(screen.getByTestId("dirty")).toHaveTextContent("false");fireEvent.click(ruleSwitch("disallow-truncate"));@@ -146,8 +172,9 @@ describe("SQLReviewStandardRulesSection", () => {);});- test("switching a rule back is not a change, and revert drops the draft", () => {+ test("switching a rule back is not a change, and revert drops the draft", async () => {render(<Harness />);+ await findSwitches();fireEvent.click(ruleSwitch("require-where"));fireEvent.click(ruleSwitch("require-where"));@@ -163,6 +190,7 @@ describe("SQLReviewStandardRulesSection", () => {test("keeps the draft when the save fails", async () => {mocks.upsertPolicy.mockRejectedValue(new Error("denied"));render(<Harness />);+ await findSwitches();fireEvent.click(ruleSwitch("require-where"));await act(async () => {@@ -173,15 +201,103 @@ describe("SQLReviewStandardRulesSection", () => {expect(mocks.pushNotification).not.toHaveBeenCalled();});+ test("a policy switched off through the API shows every rule on", async () => {+ seedWorkspaceRow(reviewRulePolicy([ReviewRuleType.SYNTAX], false));+ render(<Harness />);++ expect(await findSwitches()).toHaveLength(STANDARD_RULE_TYPES.length);+ for (const control of everySwitch()) {+ expect(control).toHaveAttribute("aria-checked", "true");+ }+ expect(+ screen.getByText("sql-review.standard-rules.running")+ ).toBeInTheDocument();+ });++ test("a failed read shows an error, and retry reads again", async () => {+ seedPolicies({});+ render(<Harness />);++ expect(await screen.findByRole("alert")).toHaveTextContent(+ "sql-review.standard-rules.load-failed"+ );+ expect(screen.queryAllByRole("switch")).toHaveLength(0);++ seedPolicies({ [WORKSPACE]: reviewRulePolicy([...STANDARD_RULE_TYPES]) });+ fireEvent.click(+ screen.getByRole("button", { name: "sql-review.standard-rules.retry" })+ );++ expect(await findSwitches()).toHaveLength(STANDARD_RULE_TYPES.length);+ expect(screen.queryByRole("alert")).not.toBeInTheDocument();+ expect(mocks.fetchPolicy).toHaveBeenLastCalledWith(+ expect.objectContaining({ parentPath: WORKSPACE, refresh: true })+ );+ });++ test("reads the workspace's row whether or not it is enforced", async () => {+ render(<Harness />);+ await findSwitches();++ expect(mocks.listPolicies).toHaveBeenCalledWith({+ parentPath: WORKSPACE,+ policyType: PolicyType.REVIEW_RULE,+ showDeleted: true,+ });+ });++ // Editing an existing row is an update; the first save creates the row.test.each([- ["bb.policies.update"],- // The first save creates the workspace's policy row.- ["bb.policies.create"],- ])("locks the switches without %s", (permission) => {- mocks.permissions = { [permission]: false };+ ["an existing row", "bb.policies.update", "bb.policies.create"],+ ["no row", "bb.policies.create", "bb.policies.update"],+ ])(+ "with %s, the switches need %s and not %s",+ async (row, needed, unneeded) => {+ if (row === "no row") {+ // GetPolicy stands in for the missing row; only the list is empty.+ mocks.listPolicies.mockResolvedValue([]);+ }+ mocks.permissions = { [needed]: false };+ const { unmount } = render(<Harness />);+ for (const control of await findSwitches()) {+ expect(control).toHaveAttribute("data-disabled");+ }+ unmount();++ mocks.permissions = { [unneeded]: false };+ render(<Harness />);+ for (const control of await findSwitches()) {+ expect(control).not.toHaveAttribute("data-disabled");+ }+ }+ );++ test.each([["bb.policies.update"], ["bb.policies.create"]])(+ "without the list permission, the switches need %s",+ async (permission) => {+ mocks.permissions = { "bb.policies.list": false, [permission]: false };+ render(<Harness />);++ for (const control of await findSwitches()) {+ expect(control).toHaveAttribute("data-disabled");+ }+ expect(mocks.listPolicies).not.toHaveBeenCalled();+ }+ );++ test("a save records the row, so later saves need only update", async () => {+ mocks.listPolicies.mockResolvedValue([]);+ mocks.permissions = { "bb.policies.update": false };render(<Harness />);+ await findSwitches();++ fireEvent.click(ruleSwitch("require-where"));+ await act(async () => {+ fireEvent.click(screen.getByText("save"));+ });- for (const control of screen.getAllByRole("switch")) {+ expect(mocks.upsertPolicy).toHaveBeenCalledTimes(1);+ for (const control of everySwitch()) {expect(control).toHaveAttribute("data-disabled");}});diff --git a/frontend/src/routes/workspace/SQLReviewStandardRulesSection.tsx b/frontend/src/routes/workspace/SQLReviewStandardRulesSection.tsxindex 3bc83026ad..a869c32688 100644--- a/frontend/src/routes/workspace/SQLReviewStandardRulesSection.tsx+++ b/frontend/src/routes/workspace/SQLReviewStandardRulesSection.tsx@@ -3,13 +3,16 @@ import { useEffect, useState } from "react";import { useTranslation } from "react-i18next";import { StandardRuleSwitches } from "@/components/sql-review/StandardRuleSwitches";import {- reviewRulesOfPolicy,+ effectiveWorkspaceRules,sameStandardRules,} from "@/components/sql-review/standardRules";+import { Alert } from "@/components/ui/alert";+import { Button } from "@/components/ui/button";import { useWorkspaceResourceName } from "@/hooks/useAppState";import { pushNotification } from "@/stores";import { useAppStore } from "@/stores/app";import {+ type Policy,PolicyResourceType,PolicyType,ReviewRulePolicySchema,@@ -18,8 +21,13 @@ import type { ReviewRuleType } from "@/types/proto-es/v1/review_rule_pb";import { hasWorkspacePermissionV2 } from "@/utils";export interface WorkspaceStandardRules {- // Undefined until the workspace policy loads.+ // The rules in force; undefined until read, or when the read failed.rules: ReviewRuleType[] | undefined;+ readFailed: boolean;+ reload: () => void;+ // Whether this user may save. The first save creates the workspace's+ // policy row and later saves update it.+ canEdit: boolean;setRules: (rules: ReviewRuleType[]) => void;isDirty: boolean;saving: boolean;@@ -34,21 +42,59 @@ export function useWorkspaceStandardRules(): WorkspaceStandardRules {const { t } = useTranslation();const workspace = useWorkspaceResourceName();+ const canCreate = hasWorkspacePermissionV2("bb.policies.create");+ const canUpdate = hasWorkspacePermissionV2("bb.policies.update");+ const canList = hasWorkspacePermissionV2("bb.policies.list");const policy = useAppStore((state) =>state.getPolicyByParentAndType({parentPath: workspace,policyType: PolicyType.REVIEW_RULE,}));+ const [attempt, setAttempt] = useState(0);+ const [readFailed, setReadFailed] = useState(false);+ // The workspace's own row, whatever its enforce flag: null when it has+ // none, undefined while unknown. GetPolicy stands in for a missing row, so+ // only the list tells them apart.+ const [row, setRow] = useState<Policy | null | undefined>(undefined);useEffect(() => {if (!enabled || !workspace) return;- void useAppStore.getState().getOrFetchPolicyByParentAndType({+ let active = true;+ setReadFailed(false);+ const store = useAppStore.getState();+ const find = {parentPath: workspace,policyType: PolicyType.REVIEW_RULE,- });- }, [enabled, workspace]);+ };+ // A read that failed leaves nothing in the cache.+ void store+ .getOrFetchPolicyByParentAndType({ ...find, refresh: attempt > 0 })+ .then(() => {+ if (active && store.getPolicyByParentAndType(find) === undefined) {+ setReadFailed(true);+ }+ });+ if (canList) {+ void store+ .listPolicies({ ...find, showDeleted: true })+ .then((policies) => {+ // A save that landed first already knows the row.+ if (active) {+ setRow((known) =>+ known === undefined ? (policies[0] ?? null) : known+ );+ }+ })+ .catch(() => {+ // Unknown keeps the conservative gate below.+ });+ }+ return () => {+ active = false;+ };+ }, [enabled, workspace, canList, attempt]);- const stored = reviewRulesOfPolicy(policy);+ const stored = effectiveWorkspaceRules(policy);const [draft, setDraft] = useState<ReviewRuleType[]>();const [saving, setSaving] = useState(false);const isDirty =@@ -60,7 +106,7 @@ export function useWorkspaceStandardRules(if (!draft) return;setSaving(true);try {- await useAppStore.getState().upsertPolicy({+ const saved = await useAppStore.getState().upsertPolicy({parentPath: workspace,policy: {type: PolicyType.REVIEW_RULE,@@ -72,6 +118,7 @@ export function useWorkspaceStandardRules(},},});+ setRow(saved);setDraft(undefined);pushNotification({module: "bytebase",@@ -86,8 +133,19 @@ export function useWorkspaceStandardRules(}};+ // Without the row known, the save may be either a create or an update.+ const canEdit =+ row === undefined+ ? canCreate && canUpdate+ : row === null+ ? canCreate+ : canUpdate;+return {rules: draft ?? stored,+ readFailed,+ reload: () => setAttempt((n) => n + 1),+ canEdit,setRules: setDraft,isDirty,saving,@@ -102,10 +160,6 @@ export function SQLReviewStandardRulesSection({standardRules: WorkspaceStandardRules;}) {const { t } = useTranslation();- // The workspace has no policy row until the first save, which creates it.- const canUpdate =- hasWorkspacePermissionV2("bb.policies.update") &&- hasWorkspacePermissionV2("bb.policies.create");return (<section className="flex flex-col gap-y-6 pt-8">@@ -117,11 +171,26 @@ export function SQLReviewStandardRulesSection({{t("sql-review.standard-rules.description")}</p></div>+ {standardRules.readFailed && (+ <Alert+ variant="error"+ description={t("sql-review.standard-rules.load-failed")}+ >+ <Button+ className="mt-3"+ appearance="outline"+ size="sm"+ onClick={standardRules.reload}+ >+ {t("sql-review.standard-rules.retry")}+ </Button>+ </Alert>+ )}{standardRules.rules && (<StandardRuleSwitchesrules={standardRules.rules}onChange={standardRules.setRules}- disabled={!canUpdate || standardRules.saving}+ disabled={!standardRules.canEdit || standardRules.saving}/>)}</section>diff --git a/frontend/src/stores/app/policy.test.ts b/frontend/src/stores/app/policy.test.tsindex 1e40287a63..3ad05022eb 100644--- a/frontend/src/stores/app/policy.test.ts+++ b/frontend/src/stores/app/policy.test.ts@@ -2,6 +2,8 @@import { create } from "@bufbuild/protobuf";import { beforeEach, describe, expect, test, vi } from "vitest";import {+ type ListPoliciesRequest,+ ListPoliciesResponseSchema,PolicyResourceType,PolicySchema,PolicyType,@@ -12,11 +14,13 @@ import { ReviewRuleType } from "@/types/proto-es/v1/review_rule_pb";import { createPolicySlice } from "./policy";const mocks = vi.hoisted(() => ({+ listPolicies: vi.fn(),updatePolicy: vi.fn(),}));vi.mock("@/api", () => ({orgPolicyServiceClientConnect: {+ listPolicies: mocks.listPolicies,updatePolicy: mocks.updatePolicy,},}));@@ -80,4 +84,28 @@ describe("policy store", () => {})?.policy.value).toEqual(expect.objectContaining({ rules: [ReviewRuleType.SYNTAX] }));});++ test("lists the rows of a parent, including ones switched off", async () => {+ const row = create(PolicySchema, {+ name: "workspaces/ws/policies/review_rule",+ type: PolicyType.REVIEW_RULE,+ enforce: false,+ });+ mocks.listPolicies.mockResolvedValue(+ create(ListPoliciesResponseSchema, { policies: [row] })+ );+ const store = createStore();++ const policies = await store.listPolicies({+ parentPath: "workspaces/ws",+ policyType: PolicyType.REVIEW_RULE,+ showDeleted: true,+ });++ const request = mocks.listPolicies.mock.calls[0][0] as ListPoliciesRequest;+ expect(request.parent).toBe("workspaces/ws");+ expect(request.policyType).toBe(PolicyType.REVIEW_RULE);+ expect(request.showDeleted).toBe(true);+ expect(policies).toEqual([row]);+ });});diff --git a/frontend/src/stores/app/policy.ts b/frontend/src/stores/app/policy.tsindex 1f584fc692..f949e71d56 100644--- a/frontend/src/stores/app/policy.ts+++ b/frontend/src/stores/app/policy.ts@@ -5,6 +5,7 @@ import { silentContextKey } from "@/api/context-key";import {DeletePolicyRequestSchema,GetPolicyRequestSchema,+ ListPoliciesRequestSchema,type Policy,PolicyResourceType,PolicySchema,@@ -160,6 +161,18 @@ export const createPolicySlice: AppSliceCreator<PolicySlice> = (set, get) => ({: EMPTY_QUERY_DATA_POLICY;},+ listPolicies: async ({ parentPath, policyType, showDeleted = false }) => {+ const { policies } = await orgPolicyServiceClientConnect.listPolicies(+ createProto(ListPoliciesRequestSchema, {+ parent: parentPath,+ policyType,+ showDeleted,+ }),+ { contextValues: createContextValues().set(silentContextKey, true) }+ );+ return policies;+ },+upsertPolicy: async ({ parentPath, policy }) => {if (!policy.type) {throw new Error("policy type is required");diff --git a/frontend/src/stores/app/types.ts b/frontend/src/stores/app/types.tsindex 26ed6bfaa4..89a65d641e 100644--- a/frontend/src/stores/app/types.ts+++ b/frontend/src/stores/app/types.ts@@ -984,6 +984,12 @@ export type PolicySlice = {refresh?: boolean;}) => Promise<Policy | undefined>;getQueryDataPolicyByParent: (parent: string) => QueryDataPolicy;+ listPolicies: (params: {+ parentPath: string;+ policyType: PolicyType;+ // Includes policies that are not enforced.+ showDeleted?: boolean;+ }) => Promise<Policy[]>;upsertPolicy: (params: {parentPath: string;policy: Partial<Policy>;