Skip to content

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

fix(review): gate each rule save on the RPC it makes

rebelicefb46a6463400
diff --git a/frontend/src/app/router/routes/dashboard.tsx b/frontend/src/app/router/routes/dashboard.tsx
index e4ad70c0e4..d74484ae00 100644
--- a/frontend/src/app/router/routes/dashboard.tsx
+++ b/frontend/src/app/router/routes/dashboard.tsx
@@ -184,10 +184,11 @@ const workspaceLevelRoutes: RouteObject[] = [
index: true,
handle: {
name: WORKSPACE_ROUTE_SQL_REVIEW,
- requiredPermissionList: (): Permission[] => [
- "bb.reviewConfigs.list",
- "bb.policies.get",
- ],
+ // The V2 page reads the review rule policy only.
+ requiredPermissionList: (): Permission[] =>
+ sqlReviewV2Enabled()
+ ? ["bb.policies.get"]
+ : ["bb.reviewConfigs.list", "bb.policies.get"],
},
lazy: lazyPage(
() => import("@/routes/workspace/SQLReviewPage"),
diff --git a/frontend/src/components/sql-review/standardRules.test.ts b/frontend/src/components/sql-review/standardRules.test.ts
index cbbee799de..e1f41e21dc 100644
--- a/frontend/src/components/sql-review/standardRules.test.ts
+++ b/frontend/src/components/sql-review/standardRules.test.ts
@@ -63,6 +63,21 @@ describe("standard rules", () => {
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(
@@ -73,6 +88,7 @@ describe("standard rules", () => {
reviewRulesOfPolicy(
create(PolicySchema, {
type: PolicyType.REVIEW_RULE,
+ enforce: true,
policy: {
case: "reviewRulePolicy",
value: create(ReviewRulePolicySchema, {
diff --git a/frontend/src/components/sql-review/standardRules.ts b/frontend/src/components/sql-review/standardRules.ts
index 9a62816333..826ee2c6d6 100644
--- a/frontend/src/components/sql-review/standardRules.ts
+++ b/frontend/src/components/sql-review/standardRules.ts
@@ -36,11 +36,12 @@ export const sameStandardRules = (
};
// The rules a cached review rule policy switches on, or undefined when the
-// resource has none of its own.
+// 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?.policy.case === "reviewRulePolicy" && policy.enforce
? sortStandardRules(policy.policy.value.rules)
: undefined;
diff --git a/frontend/src/routes/project/ProjectSQLReviewPage.test.tsx b/frontend/src/routes/project/ProjectSQLReviewPage.test.tsx
index d2953b2bc7..9f1ffcea5c 100644
--- a/frontend/src/routes/project/ProjectSQLReviewPage.test.tsx
+++ b/frontend/src/routes/project/ProjectSQLReviewPage.test.tsx
@@ -15,7 +15,7 @@ const WORKSPACE = "workspaces/ws";
const PROJECT = "projects/p";
const mocks = vi.hoisted(() => ({
- canUpdate: { value: true },
+ permissions: {} as Record<string, boolean>,
upsertPolicy: vi.fn(),
deletePolicy: vi.fn(),
fetchPolicy: vi.fn(),
@@ -39,15 +39,20 @@ vi.mock("@/hooks/useUnsavedChangesGuard", () => ({
}));
vi.mock("@/utils", () => ({
- hasProjectPermissionV2: () => mocks.canUpdate.value,
+ hasProjectPermissionV2: (_project: unknown, permission: string) =>
+ mocks.permissions[permission] ?? true,
hasWorkspacePermissionV2: () => true,
}));
vi.mock("@/stores", () => ({ pushNotification: mocks.pushNotification }));
-vi.mock("@/stores/modules/v1/common", () => ({ projectNamePrefix: "projects/" }));
+vi.mock("@/stores/modules/v1/common", () => ({
+ projectNamePrefix: "projects/",
+}));
vi.mock("@/components/RouterLink", () => ({
- RouterLink: ({ children }: { children: ReactNode }) => <a href="/">{children}</a>,
+ RouterLink: ({ children }: { children: ReactNode }) => (
+ <a href="/">{children}</a>
+ ),
}));
// Mirrors the real store: a fetch of a missing policy caches one with no
@@ -129,6 +134,7 @@ const reviewRulePolicy = (parent: string, rules: ReviewRuleType[]): Policy =>
create(PolicySchema, {
name: `${parent}/policies/review_rule`,
type: PolicyType.REVIEW_RULE,
+ enforce: true,
policy: {
case: "reviewRulePolicy",
value: create(ReviewRulePolicySchema, { rules }),
@@ -141,6 +147,12 @@ const workspacePolicy = () =>
ReviewRuleType.REQUIRE_WHERE,
]);
+const seedCustomized = () =>
+ seedPolicies({
+ [WORKSPACE]: workspacePolicy(),
+ [PROJECT]: reviewRulePolicy(PROJECT, [ReviewRuleType.SYNTAX]),
+ });
+
const renderLoaded = async () => {
render(<ProjectSQLReviewPage projectId="p" />);
return screen.findByRole("switch", {
@@ -153,6 +165,9 @@ const ruleSwitch = (rule: string) =>
name: `sql-review.standard-rules.rule.${rule}.title`,
});
+const updateButton = () =>
+ screen.queryByRole("button", { name: "common.update" });
+
const update = () =>
act(async () => {
fireEvent.click(screen.getByRole("button", { name: "common.update" }));
@@ -160,7 +175,7 @@ const update = () =>
describe("ProjectSQLReviewPage", () => {
beforeEach(() => {
- mocks.canUpdate.value = true;
+ mocks.permissions = {};
mocks.upsertPolicy.mockReset();
mocks.deletePolicy.mockReset();
mocks.fetchPolicy.mockReset();
@@ -181,12 +196,10 @@ describe("ProjectSQLReviewPage", () => {
expect(
screen.getByText("sql-review.standard-rules.running")
).toBeInTheDocument();
- expect(
- screen.queryByRole("button", { name: "common.update" })
- ).not.toBeInTheDocument();
+ expect(updateButton()).not.toBeInTheDocument();
});
- test("customizing starts from the workspace rules and saves a project policy", async () => {
+ test("customizing starts from the workspace rules and saves an enforced project policy", async () => {
const customize = await renderLoaded();
fireEvent.click(customize);
@@ -203,23 +216,19 @@ describe("ProjectSQLReviewPage", () => {
expect(parentPath).toBe(PROJECT);
expect(policy.type).toBe(PolicyType.REVIEW_RULE);
expect(policy.resourceType).toBe(PolicyResourceType.PROJECT);
+ expect(policy.enforce).toBe(true);
expect(policy.policy.value.rules).toEqual([
ReviewRuleType.SYNTAX,
ReviewRuleType.REQUIRE_WHERE,
ReviewRuleType.DISALLOW_TRUNCATE,
]);
- expect(
- screen.queryByRole("button", { name: "common.update" })
- ).not.toBeInTheDocument();
+ expect(updateButton()).not.toBeInTheDocument();
expect(customize).toHaveAttribute("aria-checked", "true");
expect(mocks.pushNotification).toHaveBeenCalledTimes(1);
});
test("turning customization off deletes the project policy", async () => {
- seedPolicies({
- [WORKSPACE]: workspacePolicy(),
- [PROJECT]: reviewRulePolicy(PROJECT, [ReviewRuleType.SYNTAX]),
- });
+ seedCustomized();
const customize = await renderLoaded();
expect(customize).toHaveAttribute("aria-checked", "true");
expect(ruleSwitch("require-where")).toHaveAttribute(
@@ -249,9 +258,7 @@ describe("ProjectSQLReviewPage", () => {
fireEvent.click(customize);
fireEvent.click(customize);
- expect(
- screen.queryByRole("button", { name: "common.update" })
- ).not.toBeInTheDocument();
+ expect(updateButton()).not.toBeInTheDocument();
});
test("a failed save keeps the draft", async () => {
@@ -261,23 +268,45 @@ describe("ProjectSQLReviewPage", () => {
fireEvent.click(customize);
await update();
- expect(
- screen.getByRole("button", { name: "common.update" })
- ).toBeInTheDocument();
+ expect(updateButton()).toBeInTheDocument();
expect(customize).toHaveAttribute("aria-checked", "true");
expect(mocks.pushNotification).not.toHaveBeenCalled();
});
- test("without bb.policies.update nothing can be switched", async () => {
- mocks.canUpdate.value = false;
- seedPolicies({
- [WORKSPACE]: workspacePolicy(),
- [PROJECT]: reviewRulePolicy(PROJECT, [ReviewRuleType.SYNTAX]),
- });
- await renderLoaded();
+ test("switching customization on needs bb.policies.create", async () => {
+ mocks.permissions = { "bb.policies.create": false };
+ const customize = await renderLoaded();
- for (const control of screen.getAllByRole("switch")) {
- expect(control).toHaveAttribute("data-disabled");
- }
+ expect(customize).toHaveAttribute("data-disabled");
+ });
+
+ test("editing the project's own rules needs bb.policies.update", async () => {
+ mocks.permissions = { "bb.policies.update": false };
+ seedCustomized();
+ const customize = await renderLoaded();
+
+ expect(ruleSwitch("require-where")).toHaveAttribute("data-disabled");
+ // Switching customization off is a delete, which this role may do.
+ expect(customize).not.toHaveAttribute("data-disabled");
+ });
+
+ test("switching customization off needs bb.policies.delete", async () => {
+ mocks.permissions = { "bb.policies.delete": false };
+ seedCustomized();
+ const customize = await renderLoaded();
+
+ expect(customize).toHaveAttribute("data-disabled");
+ expect(ruleSwitch("require-where")).not.toHaveAttribute("data-disabled");
+ });
+
+ test("undoing an unsaved switch needs no permission", async () => {
+ mocks.permissions = { "bb.policies.delete": false };
+ const customize = await renderLoaded();
+
+ fireEvent.click(customize);
+ expect(customize).not.toHaveAttribute("data-disabled");
+ fireEvent.click(customize);
+ expect(customize).toHaveAttribute("aria-checked", "false");
+ expect(updateButton()).not.toBeInTheDocument();
});
});
diff --git a/frontend/src/routes/project/ProjectSQLReviewPage.tsx b/frontend/src/routes/project/ProjectSQLReviewPage.tsx
index 22dc39f02e..91cbefe509 100644
--- a/frontend/src/routes/project/ProjectSQLReviewPage.tsx
+++ b/frontend/src/routes/project/ProjectSQLReviewPage.tsx
@@ -20,6 +20,7 @@ import { cn } from "@/lib/utils";
import { pushNotification } from "@/stores";
import { useAppStore } from "@/stores/app";
import { projectNamePrefix } from "@/stores/modules/v1/common";
+import type { Permission } from "@/types";
import {
PolicyResourceType,
PolicyType,
@@ -35,6 +36,8 @@ interface ProjectStandardRules {
// workspace.
customized: boolean;
setCustomized: (customized: boolean) => void;
+ // Whether the stored policy is the project's own; the draft may differ.
+ storedCustomized: 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;
@@ -118,6 +121,7 @@ export function useProjectStandardRules(
policy: {
type: PolicyType.REVIEW_RULE,
resourceType: PolicyResourceType.PROJECT,
+ enforce: true,
policy: {
case: "reviewRulePolicy",
value: create(ReviewRulePolicySchema, { rules: draft.rules }),
@@ -150,6 +154,7 @@ export function useProjectStandardRules(
loaded,
customized,
setCustomized,
+ storedCustomized,
rules: customized ? ownRules : workspaceRules,
setRules: (rules) => setDraft({ customized: true, rules }),
isDirty,
@@ -170,9 +175,19 @@ export function ProjectSQLReviewPage({ projectId }: { projectId: string }) {
const standardRules = useProjectStandardRules(projectName);
useUnsavedChangesGuard(standardRules.isDirty);
- const allowEdit =
- hasProjectPermissionV2(project, "bb.policies.update") &&
- !standardRules.saving;
+ 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.
+ 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;
const canViewWorkspaceRules =
hasWorkspacePermissionV2("bb.reviewConfigs.list") &&
hasWorkspacePermissionV2("bb.policies.get");
@@ -213,13 +228,13 @@ export function ProjectSQLReviewPage({ projectId }: { projectId: string }) {
}
checked={standardRules.customized}
onCheckedChange={standardRules.setCustomized}
- disabled={!allowEdit}
+ disabled={customizeLocked || standardRules.saving}
/>
{standardRules.rules && (
<StandardRuleSwitches
rules={standardRules.rules}
onChange={standardRules.setRules}
- disabled={!allowEdit}
+ disabled={rulesLocked || standardRules.saving}
readOnly={!standardRules.customized}
/>
)}
diff --git a/frontend/src/routes/workspace/SQLReviewStandardRulesSection.test.tsx b/frontend/src/routes/workspace/SQLReviewStandardRulesSection.test.tsx
index b4a74a7a24..34ebf30db6 100644
--- a/frontend/src/routes/workspace/SQLReviewStandardRulesSection.test.tsx
+++ b/frontend/src/routes/workspace/SQLReviewStandardRulesSection.test.tsx
@@ -14,7 +14,7 @@ import { ReviewRuleType } from "@/types/proto-es/v1/review_rule_pb";
const WORKSPACE = "workspaces/ws";
const mocks = vi.hoisted(() => ({
- canUpdate: { value: true },
+ permissions: {} as Record<string, boolean>,
upsertPolicy: vi.fn(),
pushNotification: vi.fn(),
}));
@@ -29,7 +29,7 @@ vi.mock("@/hooks/useAppState", () => ({
vi.mock("@/utils", () => ({
hasWorkspacePermissionV2: (permission: string) =>
- permission === "bb.policies.update" ? mocks.canUpdate.value : true,
+ mocks.permissions[permission] ?? true,
}));
vi.mock("@/stores", () => ({ pushNotification: mocks.pushNotification }));
@@ -81,6 +81,7 @@ const reviewRulePolicy = (rules: ReviewRuleType[]): Policy =>
create(PolicySchema, {
name: `${WORKSPACE}/policies/review_rule`,
type: PolicyType.REVIEW_RULE,
+ enforce: true,
policy: {
case: "reviewRulePolicy",
value: create(ReviewRulePolicySchema, { rules }),
@@ -110,13 +111,13 @@ const ruleSwitch = (rule: string) =>
describe("SQLReviewStandardRulesSection", () => {
beforeEach(() => {
- mocks.canUpdate.value = true;
+ mocks.permissions = {};
mocks.upsertPolicy.mockReset();
mocks.pushNotification.mockReset();
seedPolicies({ [WORKSPACE]: reviewRulePolicy([...STANDARD_RULE_TYPES]) });
});
- test("saves the edited rules as the workspace policy", async () => {
+ test("saves the edited rules as the enforced workspace policy", async () => {
render(<Harness />);
expect(screen.getByTestId("dirty")).toHaveTextContent("false");
@@ -132,6 +133,7 @@ describe("SQLReviewStandardRulesSection", () => {
expect(parentPath).toBe(WORKSPACE);
expect(policy.type).toBe(PolicyType.REVIEW_RULE);
expect(policy.resourceType).toBe(PolicyResourceType.WORKSPACE);
+ expect(policy.enforce).toBe(true);
expect(policy.policy.value.rules).toEqual(
STANDARD_RULE_TYPES.filter(
(rule) => rule !== ReviewRuleType.DISALLOW_TRUNCATE
@@ -171,8 +173,12 @@ describe("SQLReviewStandardRulesSection", () => {
expect(mocks.pushNotification).not.toHaveBeenCalled();
});
- test("locks the switches without bb.policies.update", () => {
- mocks.canUpdate.value = false;
+ 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 };
render(<Harness />);
for (const control of screen.getAllByRole("switch")) {
diff --git a/frontend/src/routes/workspace/SQLReviewStandardRulesSection.tsx b/frontend/src/routes/workspace/SQLReviewStandardRulesSection.tsx
index 4166555c9c..3bc83026ad 100644
--- a/frontend/src/routes/workspace/SQLReviewStandardRulesSection.tsx
+++ b/frontend/src/routes/workspace/SQLReviewStandardRulesSection.tsx
@@ -65,6 +65,7 @@ export function useWorkspaceStandardRules(
policy: {
type: PolicyType.REVIEW_RULE,
resourceType: PolicyResourceType.WORKSPACE,
+ enforce: true,
policy: {
case: "reviewRulePolicy",
value: create(ReviewRulePolicySchema, { rules: draft }),
@@ -101,7 +102,10 @@ export function SQLReviewStandardRulesSection({
standardRules: WorkspaceStandardRules;
}) {
const { t } = useTranslation();
- const canUpdate = hasWorkspacePermissionV2("bb.policies.update");
+ // 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">
diff --git a/frontend/src/stores/app/policy.test.ts b/frontend/src/stores/app/policy.test.ts
index 63f262ecb2..1e40287a63 100644
--- a/frontend/src/stores/app/policy.test.ts
+++ b/frontend/src/stores/app/policy.test.ts
@@ -55,6 +55,7 @@ describe("policy store", () => {
policy: {
type: PolicyType.REVIEW_RULE,
resourceType: PolicyResourceType.PROJECT,
+ enforce: true,
policy: {
case: "reviewRulePolicy",
value: create(ReviewRulePolicySchema, {
@@ -66,7 +67,11 @@ describe("policy store", () => {
const request = mocks.updatePolicy.mock.calls[0][0] as UpdatePolicyRequest;
expect(request.policy?.name).toBe("projects/p/policies/review_rule");
- expect(request.updateMask?.paths).toEqual(["review_rule_policy"]);
+ expect(request.policy?.enforce).toBe(true);
+ expect(request.updateMask?.paths).toEqual([
+ "review_rule_policy",
+ "enforce",
+ ]);
expect(request.allowMissing).toBe(true);
expect(
store.getPolicyByParentAndType({
diff --git a/frontend/src/stores/app/policy.ts b/frontend/src/stores/app/policy.ts
index a9b7a94894..1f584fc692 100644
--- a/frontend/src/stores/app/policy.ts
+++ b/frontend/src/stores/app/policy.ts
@@ -29,7 +29,12 @@ const getUpdateMaskFromPolicyType = (policyType: PolicyType): string[] => {
case PolicyType.TAG:
return [PolicySchema.field.tagPolicy.name];
case PolicyType.REVIEW_RULE:
- return [PolicySchema.field.reviewRulePolicy.name];
+ // Saving the rules also re-enables a policy that was switched off
+ // through the API, since the UI reads an unenforced policy as absent.
+ return [
+ PolicySchema.field.reviewRulePolicy.name,
+ PolicySchema.field.enforce.name,
+ ];
default:
throw new Error(`unexpected policy type ${policyType}`);
}