Skip to content

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

fix(review): read a policy the way the backend applies it

rebelice71046e4b484c
diff --git a/frontend/src/components/sql-review/standardRules.test.ts b/frontend/src/components/sql-review/standardRules.test.ts
index aa7f9d9619..6051f14e5a 100644
--- a/frontend/src/components/sql-review/standardRules.test.ts
+++ b/frontend/src/components/sql-review/standardRules.test.ts
@@ -77,6 +77,8 @@ describe("standard rules", () => {
name: "projects/p/policies/review_rule",
});
const switchedOff = policy(false, [ReviewRuleType.SYNTAX]);
+ // Created through the API; the backend runs nothing for it.
+ const withoutSyntax = policy(true, [ReviewRuleType.REQUIRE_WHERE]);
const customized = policy(true, [
ReviewRuleType.DISALLOW_RENAME,
ReviewRuleType.SYNTAX,
@@ -87,6 +89,7 @@ describe("standard rules", () => {
// Switched off through the API: the backend reads it as absent.
expect(reviewRulesOfPolicy(switchedOff)).toBeUndefined();
expect(reviewRulesOfPolicy(noPolicy)).toBeUndefined();
+ expect(reviewRulesOfPolicy(withoutSyntax)).toEqual([]);
expect(reviewRulesOfPolicy(customized)).toEqual([
ReviewRuleType.SYNTAX,
ReviewRuleType.DISALLOW_RENAME,
@@ -97,6 +100,7 @@ describe("standard rules", () => {
expect(storedReviewRules(undefined)).toBeUndefined();
expect(storedReviewRules(noPolicy)).toBeUndefined();
expect(storedReviewRules(switchedOff)).toEqual([ReviewRuleType.SYNTAX]);
+ expect(storedReviewRules(withoutSyntax)).toEqual([]);
expect(storedReviewRules(customized)).toEqual([
ReviewRuleType.SYNTAX,
ReviewRuleType.DISALLOW_RENAME,
@@ -106,6 +110,7 @@ describe("standard rules", () => {
test("apply every rule for a workspace without an enforced policy", () => {
expect(effectiveWorkspaceRules(undefined)).toBeUndefined();
expect(effectiveWorkspaceRules(switchedOff)).toEqual(STANDARD_RULE_TYPES);
+ expect(effectiveWorkspaceRules(withoutSyntax)).toEqual([]);
expect(effectiveWorkspaceRules(customized)).toEqual([
ReviewRuleType.SYNTAX,
ReviewRuleType.DISALLOW_RENAME,
diff --git a/frontend/src/components/sql-review/standardRules.ts b/frontend/src/components/sql-review/standardRules.ts
index 7723e48429..ff127a8740 100644
--- a/frontend/src/components/sql-review/standardRules.ts
+++ b/frontend/src/components/sql-review/standardRules.ts
@@ -35,14 +35,20 @@ export const sameStandardRules = (
);
};
-// The rules a resource's own policy row lists, whatever its enforce flag;
-// undefined when the resource has no row.
+// SYNTAX gates the rest: without it no standard rule runs.
+export const isStandardReviewOn = (rules: readonly ReviewRuleType[]): boolean =>
+ rules.includes(ReviewRuleType.SYNTAX);
+
+// The rules a resource's own policy row switches on, whatever its enforce
+// flag; undefined when the resource has no row. A list without SYNTAX runs
+// nothing, so it reads as empty, as the backend applies it.
export const storedReviewRules = (
policy: Policy | undefined
-): ReviewRuleType[] | undefined =>
- policy?.policy.case === "reviewRulePolicy"
- ? sortStandardRules(policy.policy.value.rules)
- : undefined;
+): ReviewRuleType[] | undefined => {
+ if (policy?.policy.case !== "reviewRulePolicy") return undefined;
+ const { rules } = policy.policy.value;
+ return isStandardReviewOn(rules) ? sortStandardRules(rules) : [];
+};
// 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
@@ -61,10 +67,6 @@ export const effectiveWorkspaceRules = (
? undefined
: (reviewRulesOfPolicy(policy) ?? [...STANDARD_RULE_TYPES]);
-// SYNTAX gates the rest: without it no standard rule runs.
-export const isStandardReviewOn = (rules: readonly ReviewRuleType[]): boolean =>
- rules.includes(ReviewRuleType.SYNTAX);
-
export const standardRuleText = (
t: TFunction,
rule: ReviewRuleType
diff --git a/frontend/src/locales/sql-review/en-US.json b/frontend/src/locales/sql-review/en-US.json
index 5f03fd3c81..bebcf76beb 100644
--- a/frontend/src/locales/sql-review/en-US.json
+++ b/frontend/src/locales/sql-review/en-US.json
@@ -789,7 +789,8 @@
},
"running": "{{on}} of {{total}} rules running",
"self": "Standard rules",
- "syntax-off": "Syntax is off, so none of the standard rules run. Turn Syntax on to review changes."
+ "syntax-off": "Syntax is off, so none of the standard rules run. Turn Syntax on to review changes.",
+ "workspace-rules-hidden": "You do not have permission to view the workspace rules this project follows."
},
"template": {
"bb-sql-review-dev": "Basic Template",
diff --git a/frontend/src/locales/sql-review/es-ES.json b/frontend/src/locales/sql-review/es-ES.json
index f0c568b1b3..48024d3072 100644
--- a/frontend/src/locales/sql-review/es-ES.json
+++ b/frontend/src/locales/sql-review/es-ES.json
@@ -789,7 +789,8 @@
},
"running": "{{on}} de {{total}} reglas activas",
"self": "Reglas estándar",
- "syntax-off": "La sintaxis está desactivada, por lo que no se ejecuta ninguna regla estándar. Active la sintaxis para revisar los cambios."
+ "syntax-off": "La sintaxis está desactivada, por lo que no se ejecuta ninguna regla estándar. Active la sintaxis para revisar los cambios.",
+ "workspace-rules-hidden": "No tienes permiso para ver las reglas del espacio de trabajo que sigue este proyecto."
},
"template": {
"bb-sql-review-dev": "Plantilla Básica",
diff --git a/frontend/src/locales/sql-review/ja-JP.json b/frontend/src/locales/sql-review/ja-JP.json
index 224a313625..5f9f87c37f 100644
--- a/frontend/src/locales/sql-review/ja-JP.json
+++ b/frontend/src/locales/sql-review/ja-JP.json
@@ -789,7 +789,8 @@
},
"running": "{{total}} 件中 {{on}} 件のルールが有効",
"self": "標準ルール",
- "syntax-off": "構文チェックがオフのため、標準ルールはいずれも実行されません。変更をレビューするには構文チェックをオンにしてください。"
+ "syntax-off": "構文チェックがオフのため、標準ルールはいずれも実行されません。変更をレビューするには構文チェックをオンにしてください。",
+ "workspace-rules-hidden": "このプロジェクトが従うワークスペースのルールを表示する権限がありません。"
},
"template": {
"bb-sql-review-dev": "基本的なテンプレート",
diff --git a/frontend/src/locales/sql-review/vi-VN.json b/frontend/src/locales/sql-review/vi-VN.json
index e39c7c834c..bde7a63846 100644
--- a/frontend/src/locales/sql-review/vi-VN.json
+++ b/frontend/src/locales/sql-review/vi-VN.json
@@ -789,7 +789,8 @@
},
"running": "{{on}} trên {{total}} quy tắc đang chạy",
"self": "Quy tắc tiêu chuẩn",
- "syntax-off": "Cú pháp đang tắt nên không quy tắc tiêu chuẩn nào được chạy. Hãy bật Cú pháp để đánh giá các thay đổi."
+ "syntax-off": "Cú pháp đang tắt nên không quy tắc tiêu chuẩn nào được chạy. Hãy bật Cú pháp để đánh giá các thay đổi.",
+ "workspace-rules-hidden": "Bạn không có quyền xem các quy tắc của không gian làm việc mà dự án này tuân theo."
},
"template": {
"bb-sql-review-dev": "Mẫu Cơ bản",
diff --git a/frontend/src/locales/sql-review/zh-CN.json b/frontend/src/locales/sql-review/zh-CN.json
index cd73be10c8..acf49f6c1c 100644
--- a/frontend/src/locales/sql-review/zh-CN.json
+++ b/frontend/src/locales/sql-review/zh-CN.json
@@ -789,7 +789,8 @@
},
"running": "{{total}} 条规则中 {{on}} 条生效",
"self": "标准规则",
- "syntax-off": "语法检查已关闭,所有标准规则都不会运行。开启语法检查后才会审核变更。"
+ "syntax-off": "语法检查已关闭,所有标准规则都不会运行。开启语法检查后才会审核变更。",
+ "workspace-rules-hidden": "你没有权限查看此项目所遵循的工作空间规则。"
},
"template": {
"bb-sql-review-dev": "基础模板",
diff --git a/frontend/src/routes/project/ProjectSQLReviewPage.test.tsx b/frontend/src/routes/project/ProjectSQLReviewPage.test.tsx
index cc57f16760..0846798b78 100644
--- a/frontend/src/routes/project/ProjectSQLReviewPage.test.tsx
+++ b/frontend/src/routes/project/ProjectSQLReviewPage.test.tsx
@@ -16,6 +16,7 @@ const PROJECT = "projects/p";
const mocks = vi.hoisted(() => ({
permissions: {} as Record<string, boolean>,
+ workspacePermissions: {} as Record<string, boolean>,
// Parents whose read fails: the store then caches nothing for them.
unreadable: new Set<string>(),
upsertPolicy: vi.fn(),
@@ -43,7 +44,8 @@ vi.mock("@/hooks/useUnsavedChangesGuard", () => ({
vi.mock("@/utils", () => ({
hasProjectPermissionV2: (_project: unknown, permission: string) =>
mocks.permissions[permission] ?? true,
- hasWorkspacePermissionV2: () => true,
+ hasWorkspacePermissionV2: (permission: string) =>
+ mocks.workspacePermissions[permission] ?? true,
}));
vi.mock("@/stores", () => ({ pushNotification: mocks.pushNotification }));
@@ -183,6 +185,7 @@ const update = () =>
describe("ProjectSQLReviewPage", () => {
beforeEach(() => {
mocks.permissions = {};
+ mocks.workspacePermissions = {};
mocks.unreadable.clear();
mocks.upsertPolicy.mockReset();
mocks.deletePolicy.mockReset();
@@ -380,6 +383,66 @@ describe("ProjectSQLReviewPage", () => {
});
});
+ test("a project policy without SYNTAX is customized with every rule off", async () => {
+ seedPolicies({
+ [WORKSPACE]: workspacePolicy(),
+ [PROJECT]: reviewRulePolicy(PROJECT, [ReviewRuleType.REQUIRE_WHERE]),
+ });
+ const customize = await renderLoaded();
+
+ expect(customize).toHaveAttribute("aria-checked", "true");
+ expect(ruleSwitch("require-where")).toHaveAttribute(
+ "aria-checked",
+ "false"
+ );
+ expect(
+ screen.getByText("sql-review.standard-rules.syntax-off")
+ ).toBeInTheDocument();
+ });
+
+ test("moving to another project drops the draft", async () => {
+ const { rerender } = render(<ProjectSQLReviewPage projectId="p" />);
+ const customize = await screen.findByRole("switch", {
+ name: "sql-review.standard-rules.customize.self",
+ });
+ fireEvent.click(customize);
+ expect(updateButton()).toBeInTheDocument();
+
+ rerender(<ProjectSQLReviewPage projectId="q" />);
+
+ const customizeOther = await screen.findByRole("switch", {
+ name: "sql-review.standard-rules.customize.self",
+ });
+ expect(mocks.fetchPolicy).toHaveBeenCalledWith(
+ expect.objectContaining({ parentPath: "projects/q" })
+ );
+ expect(customizeOther).toHaveAttribute("aria-checked", "false");
+ expect(updateButton()).not.toBeInTheDocument();
+ });
+
+ test("a role held only on the project loads without the workspace policy", async () => {
+ mocks.workspacePermissions = { "bb.policies.get": false };
+ const customize = await renderLoaded();
+
+ expect(mocks.fetchPolicy).not.toHaveBeenCalledWith(
+ expect.objectContaining({ parentPath: WORKSPACE })
+ );
+ expect(screen.queryByRole("alert")).toHaveTextContent(
+ "sql-review.standard-rules.workspace-rules-hidden"
+ );
+ expect(
+ screen.queryByText("sql-review.standard-rules.on")
+ ).not.toBeInTheDocument();
+
+ // Customizing starts from every rule, as nothing else is known.
+ fireEvent.click(customize);
+ expect(screen.getAllByRole("switch")).toHaveLength(12);
+ expect(ruleSwitch("disallow-truncate")).toHaveAttribute(
+ "aria-checked",
+ "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.tsx
index 5907e614fd..369e1d01ae 100644
--- a/frontend/src/routes/project/ProjectSQLReviewPage.tsx
+++ b/frontend/src/routes/project/ProjectSQLReviewPage.tsx
@@ -47,7 +47,7 @@ interface ProjectStandardRules {
// 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.
+ // workspace's, which are undefined when this user cannot read them.
rules: ReviewRuleType[] | undefined;
setRules: (rules: ReviewRuleType[]) => void;
isDirty: boolean;
@@ -78,16 +78,23 @@ export function useProjectStandardRules(
policyType: PolicyType.REVIEW_RULE,
})
);
+ // The backend checks a workspace policy at workspace scope, so a role held
+ // only on this project cannot read the rules the project follows.
+ const canReadWorkspace = hasWorkspacePermissionV2("bb.policies.get");
+ const [draft, setDraft] = useState<Draft>();
const [attempt, setAttempt] = useState(0);
const [loaded, setLoaded] = useState(false);
const [readFailed, setReadFailed] = useState(false);
useEffect(() => {
if (!workspace) return;
let active = true;
+ // The route component is reused when moving to another project.
+ setDraft(undefined);
setLoaded(false);
setReadFailed(false);
const store = useAppStore.getState();
- const finds = [projectName, workspace].map((parentPath) => ({
+ const parents = canReadWorkspace ? [projectName, workspace] : [projectName];
+ const finds = parents.map((parentPath) => ({
parentPath,
policyType: PolicyType.REVIEW_RULE,
}));
@@ -110,14 +117,15 @@ export function useProjectStandardRules(
return () => {
active = false;
};
- }, [projectName, workspace, attempt]);
+ }, [projectName, workspace, canReadWorkspace, attempt]);
const storedRules = reviewRulesOfPolicy(projectPolicy);
const hasOwnRow = storedReviewRules(projectPolicy) !== undefined;
- const workspaceRules = effectiveWorkspaceRules(workspacePolicy);
+ const workspaceRules = canReadWorkspace
+ ? effectiveWorkspaceRules(workspacePolicy)
+ : undefined;
const storedCustomized = storedRules !== undefined;
- const [draft, setDraft] = useState<Draft>();
const [saving, setSaving] = useState(false);
const revert = useCallback(() => setDraft(undefined), []);
const customized = draft?.customized ?? storedCustomized;
@@ -271,13 +279,19 @@ export function ProjectSQLReviewPage({ projectId }: { projectId: string }) {
onCheckedChange={standardRules.setCustomized}
disabled={customizeLocked || standardRules.saving}
/>
- {standardRules.rules && (
+ {standardRules.rules ? (
<StandardRuleSwitches
rules={standardRules.rules}
onChange={standardRules.setRules}
disabled={!canSave || standardRules.saving}
readOnly={!standardRules.customized}
/>
+ ) : (
+ <Alert
+ description={t(
+ "sql-review.standard-rules.workspace-rules-hidden"
+ )}
+ />
)}
</>
)}
diff --git a/frontend/src/routes/workspace/SQLReviewStandardRulesSection.test.tsx b/frontend/src/routes/workspace/SQLReviewStandardRulesSection.test.tsx
index 218ba88e55..c124f21237 100644
--- a/frontend/src/routes/workspace/SQLReviewStandardRulesSection.test.tsx
+++ b/frontend/src/routes/workspace/SQLReviewStandardRulesSection.test.tsx
@@ -214,6 +214,18 @@ describe("SQLReviewStandardRulesSection", () => {
).toBeInTheDocument();
});
+ test("a policy without SYNTAX shows every rule off", async () => {
+ seedWorkspaceRow(reviewRulePolicy([ReviewRuleType.REQUIRE_WHERE]));
+ render(<Harness />);
+
+ for (const control of await findSwitches()) {
+ expect(control).toHaveAttribute("aria-checked", "false");
+ }
+ expect(
+ screen.getByText("sql-review.standard-rules.syntax-off")
+ ).toBeInTheDocument();
+ });
+
test("a failed read shows an error, and retry reads again", async () => {
seedPolicies({});
render(<Harness />);
diff --git a/frontend/src/routes/workspace/SQLReviewStandardRulesSection.tsx b/frontend/src/routes/workspace/SQLReviewStandardRulesSection.tsx
index a869c32688..3015f7f505 100644
--- a/frontend/src/routes/workspace/SQLReviewStandardRulesSection.tsx
+++ b/frontend/src/routes/workspace/SQLReviewStandardRulesSection.tsx
@@ -57,9 +57,12 @@ export function useWorkspaceStandardRules(
// 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 = {
@@ -95,7 +98,6 @@ export function useWorkspaceStandardRules(
}, [enabled, workspace, canList, attempt]);
const stored = effectiveWorkspaceRules(policy);
- const [draft, setDraft] = useState<ReviewRuleType[]>();
const [saving, setSaving] = useState(false);
const isDirty =
draft !== undefined &&