Skip to content

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

fix(review): gate the workspace rules on update alone

rebelice2a8302b7af1a
diff --git a/frontend/src/routes/workspace/SQLReviewStandardRulesSection.test.tsx b/frontend/src/routes/workspace/SQLReviewStandardRulesSection.test.tsx
index 94f47c425f..45dd2eef2f 100644
--- a/frontend/src/routes/workspace/SQLReviewStandardRulesSection.test.tsx
+++ b/frontend/src/routes/workspace/SQLReviewStandardRulesSection.test.tsx
@@ -16,7 +16,6 @@ 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(),
}));
@@ -48,10 +47,6 @@ vi.mock("@/stores/app", async () => {
parentPath: string;
refresh?: boolean;
}) => Promise<StorePolicy | null | undefined>;
- listPolicies: (params: {
- parentPath: string;
- showDeleted?: boolean;
- }) => Promise<StorePolicy[]>;
upsertPolicy: (params: {
parentPath: string;
policy: Partial<StorePolicy>;
@@ -64,7 +59,6 @@ vi.mock("@/stores/app", async () => {
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;
@@ -102,11 +96,6 @@ const reviewRulePolicy = (
},
});
-const seedWorkspaceRow = (policy: Policy | null) => {
- seedPolicies(policy ? { [WORKSPACE]: policy } : {});
- mocks.listPolicies.mockResolvedValue(policy ? [policy] : []);
-};
-
function Harness() {
const standardRules = useWorkspaceStandardRules(true);
return (
@@ -136,10 +125,9 @@ describe("SQLReviewStandardRulesSection", () => {
beforeEach(() => {
mocks.permissions = {};
mocks.fetchPolicy.mockReset();
- mocks.listPolicies.mockReset();
mocks.upsertPolicy.mockReset();
mocks.pushNotification.mockReset();
- seedWorkspaceRow(reviewRulePolicy([...STANDARD_RULE_TYPES]));
+ seedPolicies({ [WORKSPACE]: reviewRulePolicy([...STANDARD_RULE_TYPES]) });
});
test("saves the edited rules as the enforced workspace policy", async () => {
@@ -202,7 +190,9 @@ describe("SQLReviewStandardRulesSection", () => {
});
test("a policy switched off through the API shows every rule on", async () => {
- seedWorkspaceRow(reviewRulePolicy([ReviewRuleType.SYNTAX], false));
+ seedPolicies({
+ [WORKSPACE]: reviewRulePolicy([ReviewRuleType.SYNTAX], false),
+ });
render(<Harness />);
expect(await findSwitches()).toHaveLength(STANDARD_RULE_TYPES.length);
@@ -215,7 +205,9 @@ describe("SQLReviewStandardRulesSection", () => {
});
test("a policy without SYNTAX shows every rule off", async () => {
- seedWorkspaceRow(reviewRulePolicy([ReviewRuleType.REQUIRE_WHERE]));
+ seedPolicies({
+ [WORKSPACE]: reviewRulePolicy([ReviewRuleType.REQUIRE_WHERE]),
+ });
render(<Harness />);
for (const control of await findSwitches()) {
@@ -247,70 +239,22 @@ describe("SQLReviewStandardRulesSection", () => {
);
});
- test("reads the workspace's row whether or not it is enforced", async () => {
+ test("the switches need bb.policies.update", async () => {
+ mocks.permissions = { "bb.policies.update": false };
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([
- ["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();
+ for (const control of await findSwitches()) {
+ expect(control).toHaveAttribute("data-disabled");
}
- );
+ });
- test("a save records the row, so later saves need only update", async () => {
- mocks.listPolicies.mockResolvedValue([]);
- mocks.permissions = { "bb.policies.update": false };
+ // Every workspace has a review rule policy row, so a save never creates.
+ test("the switches do not need bb.policies.create", async () => {
+ mocks.permissions = { "bb.policies.create": false };
render(<Harness />);
- await findSwitches();
-
- fireEvent.click(ruleSwitch("require-where"));
- await act(async () => {
- fireEvent.click(screen.getByText("save"));
- });
- expect(mocks.upsertPolicy).toHaveBeenCalledTimes(1);
- for (const control of everySwitch()) {
- expect(control).toHaveAttribute("data-disabled");
+ for (const control of await findSwitches()) {
+ expect(control).not.toHaveAttribute("data-disabled");
}
});
});
diff --git a/frontend/src/routes/workspace/SQLReviewStandardRulesSection.tsx b/frontend/src/routes/workspace/SQLReviewStandardRulesSection.tsx
index f9b49102a7..f647b09884 100644
--- a/frontend/src/routes/workspace/SQLReviewStandardRulesSection.tsx
+++ b/frontend/src/routes/workspace/SQLReviewStandardRulesSection.tsx
@@ -12,7 +12,6 @@ import { useWorkspaceResourceName } from "@/hooks/useAppState";
import { pushNotification } from "@/stores";
import { useAppStore } from "@/stores/app";
import {
- type Policy,
PolicyResourceType,
PolicyType,
ReviewRulePolicySchema,
@@ -25,8 +24,8 @@ export interface WorkspaceStandardRules {
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.
+ // Whether this user may save. Every workspace gets a review rule policy
+ // row by default, so a save is an update.
canEdit: boolean;
setRules: (rules: ReviewRuleType[]) => void;
isDirty: boolean;
@@ -42,9 +41,6 @@ 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,
@@ -53,46 +49,26 @@ export function useWorkspaceStandardRules(
);
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);
const [draft, setDraft] = useState<ReviewRuleType[]>();
useEffect(() => {
if (!enabled || !workspace) return;
let active = true;
setDraft(undefined);
- setRow(undefined);
setReadFailed(false);
- const store = useAppStore.getState();
- const find = {
- parentPath: workspace,
- policyType: PolicyType.REVIEW_RULE,
- };
- void store
- .fetchPolicyByParentAndType({ ...find, refresh: attempt > 0 })
+ void useAppStore
+ .getState()
+ .fetchPolicyByParentAndType({
+ parentPath: workspace,
+ policyType: PolicyType.REVIEW_RULE,
+ refresh: attempt > 0,
+ })
.then((policy) => {
if (active && policy === 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]);
+ }, [enabled, workspace, attempt]);
const stored = effectiveWorkspaceRules(policy);
const [saving, setSaving] = useState(false);
@@ -105,7 +81,7 @@ export function useWorkspaceStandardRules(
if (!draft) return;
setSaving(true);
try {
- const saved = await useAppStore.getState().upsertPolicy({
+ await useAppStore.getState().upsertPolicy({
parentPath: workspace,
policy: {
type: PolicyType.REVIEW_RULE,
@@ -117,7 +93,6 @@ export function useWorkspaceStandardRules(
},
},
});
- setRow(saved);
setDraft(undefined);
pushNotification({
module: "bytebase",
@@ -132,19 +107,11 @@ 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,
+ canEdit: hasWorkspacePermissionV2("bb.policies.update"),
setRules: setDraft,
isDirty,
saving,
diff --git a/frontend/src/stores/app/policy.test.ts b/frontend/src/stores/app/policy.test.ts
index b36a361bd6..95b635f27e 100644
--- a/frontend/src/stores/app/policy.test.ts
+++ b/frontend/src/stores/app/policy.test.ts
@@ -3,8 +3,6 @@ import { create } from "@bufbuild/protobuf";
import { Code, ConnectError } from "@connectrpc/connect";
import { beforeEach, describe, expect, test, vi } from "vitest";
import {
- type ListPoliciesRequest,
- ListPoliciesResponseSchema,
PolicyResourceType,
PolicySchema,
PolicyType,
@@ -16,14 +14,12 @@ import { createPolicySlice } from "./policy";
const mocks = vi.hoisted(() => ({
getPolicy: vi.fn(),
- listPolicies: vi.fn(),
updatePolicy: vi.fn(),
}));
vi.mock("@/api", () => ({
orgPolicyServiceClientConnect: {
getPolicy: mocks.getPolicy,
- listPolicies: mocks.listPolicies,
updatePolicy: mocks.updatePolicy,
},
}));
@@ -128,28 +124,4 @@ describe("policy store", () => {
store.getOrFetchPolicyByParentAndType(find)
).resolves.toBeUndefined();
});
-
- 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.ts
index f8213970b6..80c21aedc3 100644
--- a/frontend/src/stores/app/policy.ts
+++ b/frontend/src/stores/app/policy.ts
@@ -5,7 +5,6 @@ import { silentContextKey } from "@/api/context-key";
import {
DeletePolicyRequestSchema,
GetPolicyRequestSchema,
- ListPoliciesRequestSchema,
type Policy,
PolicyResourceType,
PolicySchema,
@@ -174,18 +173,6 @@ 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.ts
index fde8da057a..46a8e499d9 100644
--- a/frontend/src/stores/app/types.ts
+++ b/frontend/src/stores/app/types.ts
@@ -991,12 +991,6 @@ export type PolicySlice = {
refresh?: boolean;
}) => Promise<Policy | null | 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>;