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: build complex cel (#21611)
ecmadaoa1037428b9a6
diff --git a/frontend/scripts/check-ui-guideline.mjs b/frontend/scripts/check-ui-guideline.mjsindex 7bd58d071a..9751a129df 100644--- a/frontend/scripts/check-ui-guideline.mjs+++ b/frontend/scripts/check-ui-guideline.mjs@@ -15,6 +15,8 @@ const scriptDir = dirname(fileURLToPath(import.meta.url));const frontendRoot = resolve(scriptDir, "..");const sourceRoot = resolve(frontendRoot, "src");const sharedPrimitivePrefix = "src/components/ui/";+const lifecycleStampPath =+ "src/routes/project/plan-detail/components/lifecycle/LifecycleStamp.tsx";const legacyIgnoredPrefixes = ["src/apps/explain-visualizer/"];const generatedPrefixes = ["src/types/proto-es/"];@@ -246,6 +248,7 @@ const scanTextPill = (node, path, counts) => {tailwindUtility);if (+ path !== lifecycleStampPath &&tokens.includes("rounded-full") &&tokens.some((token) => /^(?:px|py)-/.test(token)) &&tokens.some((token) => /^text-(?:xs|sm)$/.test(token)) &&diff --git a/frontend/scripts/check-ui-guideline.test.mjs b/frontend/scripts/check-ui-guideline.test.mjsnew file mode 100644index 0000000000..4222900757--- /dev/null+++ b/frontend/scripts/check-ui-guideline.test.mjs@@ -0,0 +1,54 @@+import { describe, expect, test } from "vitest";+import { scanSource } from "./check-ui-guideline.mjs";++describe("check-ui-guideline", () => {+ test("rejects a hand-built text pill", () => {+ expect(+ scanSource(+ 'export const Status = () => <span className="rounded-full bg-success/10 px-1.5 py-0.5 text-xs">Active</span>;',+ "src/Status.tsx"+ )+ ).toEqual([+ {+ path: "src/Status.tsx",+ rule: "no-text-pill",+ token: "rounded-full",+ count: 1,+ },+ ]);+ });++ test("allows circular controls", () => {+ expect(+ scanSource(+ 'export const Avatar = () => <span className="size-6 rounded-full bg-accent" />;',+ "src/Avatar.tsx"+ )+ ).toEqual([]);+ });++ test("rejects a Badge that overrides the compact corner", () => {+ expect(+ scanSource(+ 'export const Status = () => <Badge className="rounded-full px-1.5 py-0.5 text-xs">Active</Badge>;',+ "src/Status.tsx"+ )+ ).toEqual([+ {+ path: "src/Status.tsx",+ rule: "no-text-pill",+ token: "rounded-full",+ count: 1,+ },+ ]);+ });++ test("allows the lifecycle status stamp pill", () => {+ expect(+ scanSource(+ 'export const Status = () => <span className="rounded-full border px-2 py-0.5 text-sm">Deployed</span>;',+ "src/routes/project/plan-detail/components/lifecycle/LifecycleStamp.tsx"+ )+ ).toEqual([]);+ });+});diff --git a/frontend/src/lib/sensitive-data/exemptionDataUtils.test.ts b/frontend/src/lib/sensitive-data/exemptionDataUtils.test.tsindex b0320c31b9..957c65c395 100644--- a/frontend/src/lib/sensitive-data/exemptionDataUtils.test.ts+++ b/frontend/src/lib/sensitive-data/exemptionDataUtils.test.ts@@ -10,6 +10,7 @@ vi.mock("@/lib/i18n", () => ({"database.columns": "Columns","common.schema": "Schema","common.table": "Table",+ "cel.condition.self": "Condition","project.masking-exemption.level": "level",};if (key === "common.n-more" && params?.n !== undefined)@@ -33,13 +34,10 @@ vi.mock("@/lib/i18n", () => ({import {generateGrantTitle,- generateMemberScopeSummary,getConditionExpression,groupByMember,parseClassificationLevel,parseExpirationTimestamp,- resourceCoversDatabase,- rewriteResourceDatabase,} from "./exemptionDataUtils";import type { AccessUser, ExemptionGrant } from "./types";@@ -180,32 +178,13 @@ describe("parseExpirationTimestamp", () => {});});-describe("generateMemberScopeSummary", () => {- test("shows the database name only for a single database", () => {- expect(generateMemberScopeSummary(3, ["bytebase_210"])).toBe(- "3 exemptions · bytebase_210"- );- });-- test("shows a database count for multiple databases", () => {- expect(- generateMemberScopeSummary(3, ["bytebase_210", "bytebase_211"])- ).toBe("3 exemptions · 2 databases");- });-- test("uses all databases when any grant has global scope", () => {- expect(generateMemberScopeSummary(3, ["", "bytebase_210"])).toBe(- "3 exemptions · All databases"- );- });-});-describe("groupByMember", () => {const makeAccessUser = (overrides: Partial<AccessUser>): AccessUser => ({type: "user",member: "user:[email protected]",rawExpression: "",description: "",+ databaseResources: [],conditionExpression: "",...overrides,});@@ -332,6 +311,18 @@ describe("groupByMember", () => {expect(result[0].databaseNames).toEqual([""]);});+ test("does not summarize an unknown condition as all databases", () => {+ const result = groupByMember([+ makeAccessUser({+ databaseResources: undefined,+ conditionExpression:+ '(resource.database_name in ["a", "b"]) && (resource.column_name in ["email", "phone"])',+ }),+ ]);++ expect(result[0].databaseNames).toEqual([]);+ });+test("extracts unique database names from resources", () => {const users: AccessUser[] = [makeAccessUser({@@ -606,12 +597,19 @@ describe("generateGrantTitle", () => {id: "test",description: "",rawExpression: "",+ databaseResources: [],conditionExpression: "",...overrides,});// --- No databases ---+ test("unknown condition → Condition", () => {+ expect(+ generateGrantTitle(makeGrant({ databaseResources: undefined }))+ ).toBe("Condition");+ });+test("no resources, no level → All databases", () => {expect(generateGrantTitle(makeGrant({}))).toBe("All databases");});@@ -636,6 +634,18 @@ describe("generateGrantTitle", () => {).toBe("All databases (columns: email, phone)");});+ test("keeps the global scope visible beside database-specific resources", () => {+ expect(+ generateGrantTitle(+ makeGrant({+ databaseResources: [+ { databaseFullName: "", columns: ["email"] },+ { databaseFullName: "instances/a/databases/hr_prod" },+ ],+ })+ )+ ).toBe("All databases (columns: email); hr_prod");+ });// --- Multiple databases ---test("2 databases", () => {@@ -1031,67 +1041,6 @@ describe("generateGrantTitle", () => {});});-describe("resourceCoversDatabase", () => {- test("a column-only resource covers every database", () => {- expect(- resourceCoversDatabase(- { databaseFullName: "", columns: ["email"] },- "instances/prod/databases/hr"- )- ).toBe(true);- });-- test("an instance-only resource covers only that instance", () => {- expect(- resourceCoversDatabase(- { databaseFullName: "", instanceResourceId: "prod" },- "instances/prod/databases/hr"- )- ).toBe(true);- expect(- resourceCoversDatabase(- { databaseFullName: "", instanceResourceId: "prod" },- "instances/dev/databases/hr"- )- ).toBe(false);- });-});--describe("rewriteResourceDatabase", () => {- test("rewrites single resource.database condition", () => {- const input =- 'resource.database == "instances/prod-instance/databases/hr_prod"';- expect(rewriteResourceDatabase(input)).toBe(- 'resource.instance_id == "prod-instance" && resource.database_name == "hr_prod"'- );- });-- test("rewrites multiple resource.database conditions", () => {- const input =- '(resource.database == "instances/a/databases/db1") || (resource.database == "instances/b/databases/db2")';- expect(rewriteResourceDatabase(input)).toBe(- '(resource.instance_id == "a" && resource.database_name == "db1") || (resource.instance_id == "b" && resource.database_name == "db2")'- );- });-- test("preserves expressions without resource.database", () => {- const input = "resource.classification_level <= 3";- expect(rewriteResourceDatabase(input)).toBe(input);- });-- test("handles mixed conditions", () => {- const input =- 'resource.database == "instances/prod/databases/users" && resource.classification_level <= 2';- expect(rewriteResourceDatabase(input)).toBe(- 'resource.instance_id == "prod" && resource.database_name == "users" && resource.classification_level <= 2'- );- });-- test("handles empty string", () => {- expect(rewriteResourceDatabase("")).toBe("");- });-});-// ============================================================// BYT-9788 — composite (OR) exemption precedence & read-path round-trip//diff --git a/frontend/src/lib/sensitive-data/exemptionDataUtils.ts b/frontend/src/lib/sensitive-data/exemptionDataUtils.tsindex 3fc57e5dc8..053ca17ad2 100644--- a/frontend/src/lib/sensitive-data/exemptionDataUtils.ts+++ b/frontend/src/lib/sensitive-data/exemptionDataUtils.ts@@ -1,6 +1,4 @@import i18n from "@/lib/i18n";-import type { DatabaseResource } from "@/types/member";-import { celString } from "@/utils/v1/celLiteral";import type {AccessUser,ClassificationLevel,@@ -70,7 +68,10 @@ function listItems(items: string[]): string {}export function generateGrantTitle(grant: ExemptionGrant): string {- const resources = grant.databaseResources ?? [];+ if (!grant.databaseResources) {+ return i18n.t("cel.condition.self");+ }+ const resources = grant.databaseResources;const level = grant.classificationLevel;const levelSuffix = level@@ -81,10 +82,13 @@ export function generateGrantTitle(grant: ExemptionGrant): string {const dbName = extractDatabaseName(r.databaseFullName);return dbName !== "";});+ const globalResources = resources.filter(+ (resource) => extractDatabaseName(resource.databaseFullName) === ""+ );if (realResources.length === 0) {const columns = [- ...new Set(resources.flatMap((resource) => resource.columns ?? [])),+ ...new Set(globalResources.flatMap((resource) => resource.columns ?? [])),];const columnSuffix =columns.length > 0@@ -100,6 +104,17 @@ export function generateGrantTitle(grant: ExemptionGrant): string {),];+ if (globalResources.length > 0) {+ const columns = [+ ...new Set(globalResources.flatMap((resource) => resource.columns ?? [])),+ ];+ const columnSuffix =+ columns.length > 0+ ? ` (${i18n.t("database.columns").toLowerCase()}: ${listItems(columns)})`+ : "";+ return `${i18n.t("database.all")}${columnSuffix}; ${listItems(dbNames)}${levelSuffix}`;+ }+// Multiple databases: show first 2, no table/schema detailif (dbNames.length > 1) {return `${listItems(dbNames)}${levelSuffix}`;@@ -178,38 +193,6 @@ export function generateGrantTitle(grant: ExemptionGrant): string {return `${dbName} (${table}: ${listItems(columns)})${levelSuffix}`;}-export function resourceCoversDatabase(- resource: DatabaseResource,- databaseFullName: string-): boolean {- if (resource.databaseFullName !== "") {- return resource.databaseFullName === databaseFullName;- }- const target = databaseFullName.match(databaseResourcePattern)?.groups;- return (- (!resource.instanceResourceId ||- resource.instanceResourceId === target?.instanceName) &&- (!resource.databaseResourceId ||- resource.databaseResourceId === target?.databaseName)- );-}--// Rewrite `resource.database == "instances/X/databases/Y"` to-// `resource.instance_id == "X" && resource.database_name == "Y"`.-// The expression editor uses resource.database as a combined selector,-// but the backend masking exemption evaluator only knows individual attributes.-export function rewriteResourceDatabase(expression: string): string {- return expression.replaceAll(- /resource\.database\s*==\s*"([^"]+)"/g,- (_match, fullPath: string) => {- const matches = fullPath.match(databaseResourcePattern);- const instanceName = matches?.groups?.instanceName ?? "";- const databaseName = matches?.groups?.databaseName ?? "";- return `resource.instance_id == ${celString(instanceName)} && resource.database_name == ${celString(databaseName)}`;- }- );-}-export function buildMemberSummary(grants: ExemptionGrant[]): {databaseNames: string[];neverExpires: boolean;@@ -224,11 +207,9 @@ export function buildMemberSummary(grants: ExemptionGrant[]): {)),];- // Grants with no databaseResources cover all databases — add empty sentinel+ // Grants with an empty resource list cover all databases — add empty sentinel// so the member item can detect and display "All databases".- if (- grants.some((g) => !g.databaseResources || g.databaseResources.length === 0)- ) {+ if (grants.some((grant) => grant.databaseResources?.length === 0)) {databaseNames.push("");}const expiringGrants = grants.filter((g) => g.expirationTimestamp);@@ -242,28 +223,6 @@ export function buildMemberSummary(grants: ExemptionGrant[]): {};}-export function generateMemberScopeSummary(- grantCount: number,- databaseNames: string[]-): string {- const exemptionCount = i18n.t("project.masking-exemption.n-exemptions", {- count: grantCount,- n: grantCount,- });- const uniqueDatabases = [...new Set(databaseNames)];- if (uniqueDatabases.includes("")) {- return `${exemptionCount} · ${i18n.t("database.all")}`;- }- if (uniqueDatabases.length === 1) {- return `${exemptionCount} · ${uniqueDatabases[0]}`;- }- if (uniqueDatabases.length > 1) {- const databaseCount = uniqueDatabases.length;- return `${exemptionCount} · ${i18n.t("project.masking-exemption.n-databases", { count: databaseCount, n: databaseCount })}`;- }- return exemptionCount;-}-export function groupByMember(accessUsers: AccessUser[]): ExemptionMember[] {// Track each member's entries and the index of their last (most recent) entryconst memberMap = new Map<diff --git a/frontend/src/lib/sensitive-data/maskingExemption.test.ts b/frontend/src/lib/sensitive-data/maskingExemption.test.tsindex 13dfa73f02..d44d963c0d 100644--- a/frontend/src/lib/sensitive-data/maskingExemption.test.ts+++ b/frontend/src/lib/sensitive-data/maskingExemption.test.ts@@ -1,8 +1,22 @@// @vitest-environment nodeimport { describe, expect, test } from "vitest";-import { emptySimpleExpr, wrapAsGroup } from "@/modules/cel";+import {+ type ConditionGroupExpr,+ ExprType,+ emptySimpleExpr,+ wrapAsGroup,+} from "@/modules/cel";import type { DatabaseResource } from "@/types";-import { buildMaskingExemption } from "./maskingExemption";+import {+ CEL_ATTRIBUTE_RESOURCE_COLUMN_NAME,+ CEL_ATTRIBUTE_RESOURCE_DATABASE,+ CEL_ATTRIBUTE_RESOURCE_DATABASE_NAME,+ CEL_ATTRIBUTE_RESOURCE_INSTANCE_ID,+} from "@/utils/cel-attributes";+import {+ buildMaskingExemption,+ rewriteMaskingExemptionDatabaseConditions,+} from "./maskingExemption";const expr = wrapAsGroup(emptySimpleExpr());@@ -77,4 +91,76 @@ describe("buildMaskingExemption", () => {'((resource.instance_id == "prod" && resource.database_name == "hr") || (resource.instance_id == "test" && resource.database_name == "finance"))');});++ test("rewrites a database picker membership condition for the backend", () => {+ const expression: ConditionGroupExpr = {+ type: ExprType.ConditionGroup,+ operator: "_&&_",+ args: [+ {+ type: ExprType.Condition,+ operator: "@in",+ args: [+ CEL_ATTRIBUTE_RESOURCE_DATABASE,+ ["instances/prod/databases/hr", "instances/test/databases/finance"],+ ],+ },+ {+ type: ExprType.Condition,+ operator: "@in",+ args: [CEL_ATTRIBUTE_RESOURCE_COLUMN_NAME, ["email", "phone"]],+ },+ ],+ };++ expect(rewriteMaskingExemptionDatabaseConditions(expression)).toEqual({+ type: ExprType.ConditionGroup,+ operator: "_&&_",+ args: [+ {+ type: ExprType.ConditionGroup,+ operator: "_||_",+ args: [+ {+ type: ExprType.ConditionGroup,+ operator: "_&&_",+ args: [+ {+ type: ExprType.Condition,+ operator: "_==_",+ args: [CEL_ATTRIBUTE_RESOURCE_INSTANCE_ID, "prod"],+ },+ {+ type: ExprType.Condition,+ operator: "_==_",+ args: [CEL_ATTRIBUTE_RESOURCE_DATABASE_NAME, "hr"],+ },+ ],+ },+ {+ type: ExprType.ConditionGroup,+ operator: "_&&_",+ args: [+ {+ type: ExprType.Condition,+ operator: "_==_",+ args: [CEL_ATTRIBUTE_RESOURCE_INSTANCE_ID, "test"],+ },+ {+ type: ExprType.Condition,+ operator: "_==_",+ args: [CEL_ATTRIBUTE_RESOURCE_DATABASE_NAME, "finance"],+ },+ ],+ },+ ],+ },+ {+ type: ExprType.Condition,+ operator: "@in",+ args: [CEL_ATTRIBUTE_RESOURCE_COLUMN_NAME, ["email", "phone"]],+ },+ ],+ });+ });});diff --git a/frontend/src/lib/sensitive-data/maskingExemption.ts b/frontend/src/lib/sensitive-data/maskingExemption.tsindex 3cdc164adf..33e4c6cc8c 100644--- a/frontend/src/lib/sensitive-data/maskingExemption.ts+++ b/frontend/src/lib/sensitive-data/maskingExemption.ts@@ -1,7 +1,13 @@import { create } from "@bufbuild/protobuf";import { useMemo } from "react";-import type { ConditionGroupExpr, Factor, Operator } from "@/modules/cel";-import { buildCELExpr } from "@/modules/cel";+import type {+ ConditionExpr,+ ConditionGroupExpr,+ Factor,+ Operator,+ SimpleExpr,+} from "@/modules/cel";+import { buildCELExpr, ExprType } from "@/modules/cel";import { useAppStore } from "@/stores/app";import type { DatabaseResource } from "@/types";import { ExprSchema } from "@/types/proto-es/google/type/expr_pb";@@ -11,18 +17,20 @@ import {} from "@/types/proto-es/v1/org_policy_service_pb";import {batchConvertParsedExprToCELString,+ extractDatabaseResourceName,getDatabaseNameOptionConfig,} from "@/utils";import {CEL_ATTRIBUTE_RESOURCE_CLASSIFICATION_LEVEL,CEL_ATTRIBUTE_RESOURCE_COLUMN_NAME,CEL_ATTRIBUTE_RESOURCE_DATABASE,+ CEL_ATTRIBUTE_RESOURCE_DATABASE_NAME,+ CEL_ATTRIBUTE_RESOURCE_INSTANCE_ID,CEL_ATTRIBUTE_RESOURCE_SCHEMA_NAME,CEL_ATTRIBUTE_RESOURCE_TABLE_NAME,} from "@/utils/cel-attributes";import type { OptionConfig } from "@/utils/expr";import { getClassificationLevelOptions } from "./components-utils";-import { rewriteResourceDatabase } from "./exemptionDataUtils";import { getExpressionsForDatabaseResource } from "./utils";export type MaskingExemptionResourceMode = "ALL" | "EXPRESSION" | "SELECT";@@ -52,13 +60,14 @@ export const buildMaskingExemption = async ({}if (radioValue === "EXPRESSION") {- const parsedExpr = await buildCELExpr(expr);+ const parsedExpr = await buildCELExpr(+ rewriteMaskingExemptionDatabaseConditions(expr)+ );if (!parsedExpr) {throw new Error("Invalid masking exemption expression");}- let [celString] = await batchConvertParsedExprToCELString([parsedExpr]);- celString = rewriteResourceDatabase(celString);+ const [celString] = await batchConvertParsedExprToCELString([parsedExpr]);if (celString) {extraExpressions.push(`(${celString})`);}@@ -92,6 +101,88 @@ export const buildMaskingExemption = async ({});};+const createDatabaseScopeExpr = (+ databaseFullName: string+): ConditionGroupExpr | undefined => {+ const { database, instanceName, databaseName } =+ extractDatabaseResourceName(databaseFullName);+ if (database !== databaseFullName) {+ return undefined;+ }++ return {+ type: ExprType.ConditionGroup,+ operator: "_&&_",+ args: [+ {+ type: ExprType.Condition,+ operator: "_==_",+ args: [CEL_ATTRIBUTE_RESOURCE_INSTANCE_ID, instanceName],+ },+ {+ type: ExprType.Condition,+ operator: "_==_",+ args: [CEL_ATTRIBUTE_RESOURCE_DATABASE_NAME, databaseName],+ },+ ],+ };+};++const rewriteDatabaseCondition = (condition: ConditionExpr): SimpleExpr => {+ if (condition.args[0] !== CEL_ATTRIBUTE_RESOURCE_DATABASE) {+ return condition;+ }++ const value = condition.args[1];+ let databaseFullNames: string[] | undefined;+ if (condition.operator === "_==_" && typeof value === "string") {+ databaseFullNames = [value];+ } else if (+ condition.operator === "@in" &&+ Array.isArray(value) &&+ value.every((database) => typeof database === "string")+ ) {+ databaseFullNames = value;+ }+ if (!databaseFullNames) {+ return condition;+ }++ const databaseScopes = databaseFullNames.map(createDatabaseScopeExpr);+ if (+ !databaseScopes.every(+ (scope): scope is ConditionGroupExpr => scope !== undefined+ )+ ) {+ return condition;+ }++ return {+ type: ExprType.ConditionGroup,+ operator: "_||_",+ args: databaseScopes,+ };+};++const rewriteDatabaseExpr = (expr: SimpleExpr): SimpleExpr => {+ if (expr.type === ExprType.ConditionGroup) {+ return {+ ...expr,+ args: expr.args.map(rewriteDatabaseExpr),+ };+ }+ if (expr.type === ExprType.Condition) {+ return rewriteDatabaseCondition(expr);+ }+ return expr;+};++// The editor's database picker uses a canonical database resource name, while+// masking-exemption CEL accepts the instance and database-name attributes.+export const rewriteMaskingExemptionDatabaseConditions = (+ expr: ConditionGroupExpr+): ConditionGroupExpr => rewriteDatabaseExpr(expr) as ConditionGroupExpr;+export const useMaskingExemptionExprConfig = (projectName: string): {diff --git a/frontend/src/lib/sensitive-data/types.ts b/frontend/src/lib/sensitive-data/types.tsindex e468e0ec0b..581bd045c5 100644--- a/frontend/src/lib/sensitive-data/types.ts+++ b/frontend/src/lib/sensitive-data/types.ts@@ -34,6 +34,8 @@ export interface ExemptionGrant {description: string;expirationTimestamp?: number;rawExpression: string;+ // Undefined when the CEL scope cannot be summarized; an empty list covers+ // all databases.databaseResources?: DatabaseResource[];// The condition portion of the CEL expression, excluding request.time.// Used as fallback display when databaseResources can't be parsed.diff --git a/frontend/src/routes/project/ProjectMaskingExemptionCreatePage.test.tsx b/frontend/src/routes/project/ProjectMaskingExemptionCreatePage.test.tsxindex 06702b978e..e63bc2adbe 100644--- a/frontend/src/routes/project/ProjectMaskingExemptionCreatePage.test.tsx+++ b/frontend/src/routes/project/ProjectMaskingExemptionCreatePage.test.tsx@@ -43,6 +43,10 @@ vi.mock("react-i18next", () => ({}));vi.mock("@/modules/cel", () => ({+ ExprType: {+ Condition: "Condition",+ ConditionGroup: "ConditionGroup",+ },buildCELExpr: mocks.buildCELExpr,emptySimpleExpr: vi.fn(() => ({ type: "ConditionGroup", args: [] })),validateSimpleExpr: vi.fn(() => true),@@ -203,12 +207,15 @@ vi.mock("@/stores/app", () => ({vi.mock("@/utils", () => ({batchConvertParsedExprToCELString: mocks.batchConvertParsedExprToCELString,+ extractDatabaseResourceName: vi.fn(),getDatabaseNameOptionConfig: vi.fn(() => ({ options: [] })),}));vi.mock("@/utils/cel-attributes", () => ({CEL_ATTRIBUTE_RESOURCE_DATABASE: "resource.database",+ CEL_ATTRIBUTE_RESOURCE_DATABASE_NAME: "resource.database_name",CEL_ATTRIBUTE_RESOURCE_TABLE_NAME: "resource.table_name",+ CEL_ATTRIBUTE_RESOURCE_INSTANCE_ID: "resource.instance_id",CEL_ATTRIBUTE_RESOURCE_SCHEMA_NAME: "resource.schema_name",CEL_ATTRIBUTE_RESOURCE_COLUMN_NAME: "resource.column_name",CEL_ATTRIBUTE_RESOURCE_CLASSIFICATION_LEVEL: "resource.classification_level",diff --git a/frontend/src/routes/project/ProjectMaskingExemptionPage.tsx b/frontend/src/routes/project/ProjectMaskingExemptionPage.tsxindex e8380ed18c..d91443030d 100644--- a/frontend/src/routes/project/ProjectMaskingExemptionPage.tsx+++ b/frontend/src/routes/project/ProjectMaskingExemptionPage.tsx@@ -35,11 +35,9 @@ import { useTimeReading } from "@/hooks/useTimeReading";import {buildMemberSummary,generateGrantTitle,- generateMemberScopeSummary,getConditionExpression,groupByMember,parseExpirationTimestamp,- resourceCoversDatabase,} from "@/lib/sensitive-data/exemptionDataUtils";import type {AccessUser,@@ -73,6 +71,10 @@ import {type ConditionExpression,} from "@/utils/issue/cel";import { extractDatabaseResourceName } from "@/utils/v1/database";+import {+ generateMemberScopeSummary,+ resourceCoversDatabase,+} from "./utils/maskingExemption";// ============================================================// Helpers@@ -520,7 +522,7 @@ export function ProjectMaskingExemptionPage({function getAccessUsers(exemption: MaskingExemptionPolicy_Exemption,- condition: ConditionExpression+ condition: ConditionExpression | undefined): AccessUser[] {const expression = exemption.condition?.expression ?? "";const description = exemption.condition?.description ?? "";@@ -535,10 +537,7 @@ function getAccessUsers(expirationTimestamp,rawExpression: expression,description,- databaseResources:- condition.databaseResources && condition.databaseResources.length > 0- ? condition.databaseResources- : undefined,+ databaseResources: condition?.databaseResources,conditionExpression,}));}@@ -884,11 +883,8 @@ function ExemptionMemberItem({);const scopeSummary = useMemo(() => {- return generateMemberScopeSummary(- member.grants.length,- member.databaseNames- );- }, [member]);+ return generateMemberScopeSummary(t, member.grants, member.databaseNames);+ }, [member, t]);const handleClick = () => {if (expandable) {diff --git a/frontend/src/routes/project/database-detail/catalog/GrantAccessDialog.test.tsx b/frontend/src/routes/project/database-detail/catalog/GrantAccessDialog.test.tsxindex 7d610050bb..989eb32802 100644--- a/frontend/src/routes/project/database-detail/catalog/GrantAccessDialog.test.tsx+++ b/frontend/src/routes/project/database-detail/catalog/GrantAccessDialog.test.tsx@@ -265,6 +265,7 @@ vi.mock("@/stores/app", () => ({vi.mock("@/utils", () => ({batchConvertParsedExprToCELString: vi.fn(),+ extractDatabaseResourceName: vi.fn(),getDatabaseNameOptionConfig: vi.fn(() => ({ options: [] })),}));diff --git a/frontend/src/routes/project/database-detail/catalog/GrantAccessDialog.tsx b/frontend/src/routes/project/database-detail/catalog/GrantAccessDialog.tsxindex 81c5612352..11f2eb5d4b 100644--- a/frontend/src/routes/project/database-detail/catalog/GrantAccessDialog.tsx+++ b/frontend/src/routes/project/database-detail/catalog/GrantAccessDialog.tsx@@ -254,7 +254,7 @@ export function GrantAccessDialog({if (!parsedExpr) {return;}- return convertFromExpr(parsedExpr).databaseResources;+ return convertFromExpr(parsedExpr)?.databaseResources;} catch {return;}diff --git a/frontend/src/routes/project/utils/maskingExemption.test.ts b/frontend/src/routes/project/utils/maskingExemption.test.tsnew file mode 100644index 0000000000..bf0a80492a--- /dev/null+++ b/frontend/src/routes/project/utils/maskingExemption.test.ts@@ -0,0 +1,72 @@+import type { TFunction } from "i18next";+import { describe, expect, test } from "vitest";+import type { ExemptionGrant } from "@/lib/sensitive-data/types";+import {+ generateMemberScopeSummary,+ resourceCoversDatabase,+} from "./maskingExemption";++const t = ((key: string, options?: Record<string, unknown>) => {+ if (key === "database.all") return "All databases";+ if (key === "cel.condition.self") return "Condition";+ if (key === "project.masking-exemption.n-exemptions") {+ const count = options?.count;+ return `${count} exemption${count === 1 ? "" : "s"}`;+ }+ if (key === "project.masking-exemption.n-databases") {+ const count = options?.count;+ return `${count} database${count === 1 ? "" : "s"}`;+ }+ return key;+}) as TFunction;++const grants = (+ count: number,+ databaseResources: ExemptionGrant["databaseResources"]+) =>+ Array.from({ length: count }, () => ({+ databaseResources,+ })) as ExemptionGrant[];++describe("generateMemberScopeSummary", () => {+ test("uses the active translator for the summary", () => {+ expect(generateMemberScopeSummary(t, grants(3, []), ["bytebase_210"])).toBe(+ "3 exemptions · bytebase_210"+ );+ });++ test("shows all databases when any grant has global scope", () => {+ expect(+ generateMemberScopeSummary(t, grants(3, []), ["", "bytebase_210"])+ ).toBe("3 exemptions · All databases");+ });++ test("shows a condition when any grant cannot be summarized", () => {+ expect(+ generateMemberScopeSummary(t, grants(1, undefined), ["bytebase_210"])+ ).toBe("1 exemption · Condition");+ });+});++describe("resourceCoversDatabase", () => {+ test("matches global and instance-scoped resources", () => {+ expect(+ resourceCoversDatabase(+ { databaseFullName: "", columns: ["email"] },+ "instances/prod/databases/hr"+ )+ ).toBe(true);+ expect(+ resourceCoversDatabase(+ { databaseFullName: "", instanceResourceId: "prod" },+ "instances/prod/databases/hr"+ )+ ).toBe(true);+ expect(+ resourceCoversDatabase(+ { databaseFullName: "", instanceResourceId: "prod" },+ "instances/dev/databases/hr"+ )+ ).toBe(false);+ });+});diff --git a/frontend/src/routes/project/utils/maskingExemption.ts b/frontend/src/routes/project/utils/maskingExemption.tsnew file mode 100644index 0000000000..3bb4534db0--- /dev/null+++ b/frontend/src/routes/project/utils/maskingExemption.ts@@ -0,0 +1,51 @@+import type { TFunction } from "i18next";+import type { ExemptionGrant } from "@/lib/sensitive-data/types";+import type { DatabaseResource } from "@/types";+import { extractDatabaseResourceName } from "@/utils/v1/database";++export const resourceCoversDatabase = (+ resource: DatabaseResource,+ databaseFullName: string+): boolean => {+ if (resource.databaseFullName) {+ return resource.databaseFullName === databaseFullName;+ }+ const { instanceName, databaseName } =+ extractDatabaseResourceName(databaseFullName);+ return (+ (!resource.instanceResourceId ||+ resource.instanceResourceId === instanceName) &&+ (!resource.databaseResourceId ||+ resource.databaseResourceId === databaseName)+ );+};++export const generateMemberScopeSummary = (+ t: TFunction,+ grants: ExemptionGrant[],+ databaseNames: string[]+): string => {+ const grantCount = grants.length;+ const exemptionCount = t("project.masking-exemption.n-exemptions", {+ count: grantCount,+ n: grantCount,+ });+ const uniqueDatabases = [...new Set(databaseNames)];+ if (grants.some((grant) => grant.databaseResources === undefined)) {+ return `${exemptionCount} · ${t("cel.condition.self")}`;+ }+ if (uniqueDatabases.includes("")) {+ return `${exemptionCount} · ${t("database.all")}`;+ }+ if (uniqueDatabases.length === 1) {+ return `${exemptionCount} · ${uniqueDatabases[0]}`;+ }+ if (uniqueDatabases.length > 1) {+ const databaseCount = uniqueDatabases.length;+ return `${exemptionCount} · ${t("project.masking-exemption.n-databases", {+ count: databaseCount,+ n: databaseCount,+ })}`;+ }+ return exemptionCount;+};diff --git a/frontend/src/routes/workspace/MembersPage.tsx b/frontend/src/routes/workspace/MembersPage.tsxindex ee3ba5ea79..b2324b100f 100644--- a/frontend/src/routes/workspace/MembersPage.tsx+++ b/frontend/src/routes/workspace/MembersPage.tsx@@ -1458,7 +1458,7 @@ function EditMemberRoleDrawer({expiration?: Date;}[] => {if (!binding.parsedExpr) return [{}];- const conditionExpr = convertFromExpr(binding.parsedExpr);+ const conditionExpr = convertFromExpr(binding.parsedExpr) ?? {};const base: { expiration?: Date } = {};if (conditionExpr.expiredTime)base.expiration = new Date(conditionExpr.expiredTime);diff --git a/frontend/src/utils/issue/cel.test.ts b/frontend/src/utils/issue/cel.test.tsindex 0f86a5dfe0..32ee03622c 100644--- a/frontend/src/utils/issue/cel.test.ts+++ b/frontend/src/utils/issue/cel.test.ts@@ -6,6 +6,7 @@ import {} from "@/types/proto-es/google/api/expr/v1alpha1/syntax_pb";import {convertFromExpr,+ getGuaranteedExpiration,readableCondition,stringifyConditionExpression,} from "./cel";@@ -93,7 +94,7 @@ describe("readableCondition proves the environments and keeps the rest best-effo});test("a clause under || or ! does not count: `in [] || true` is not the switch off", () => {- expect(convertFromExpr(or(envIn(), bool(true))).environments).toEqual([]);+ expect(convertFromExpr(or(envIn(), bool(true)))?.environments).toEqual([]);expect(environments(or(envIn(), bool(true)))).toBeUndefined();expect(environments(or(envIn("prod"), envIn("dev")))).toBeUndefined();expect(@@ -124,11 +125,34 @@ describe("readableCondition proves the environments and keeps the rest best-effo});});+describe("getGuaranteedExpiration", () => {+ test("finds an expiration beside independent disjunctions", () => {+ const expiration = "2020-01-01T00:00:00Z";+ expect(+ getGuaranteedExpiration(+ and(+ or(eq("database", "instances/i/databases/a"), eq("database", A)),+ or(eq("schema_name", "public"), eq("schema_name", "internal")),+ timeBefore(expiration)+ )+ )?.toISOString()+ ).toBe("2020-01-01T00:00:00.000Z");+ });++ test("ignores an expiration that is only one OR branch", () => {+ expect(+ getGuaranteedExpiration(+ or(timeBefore("2020-01-01T00:00:00Z"), eq("database", A))+ )+ ).toBeUndefined();+ });+});+describe("convertFromExpr with a column condition", () => {const columnIn = (...names: string[]) =>call("@in", resource("column_name"), list(...names.map(str)));const databaseResources = (expr: Expr) =>- convertFromExpr(expr).databaseResources;+ convertFromExpr(expr)?.databaseResources;test("keeps the columns of a column-only in condition", () => {expect(databaseResources(columnIn("email", "phone"))).toEqual([@@ -166,4 +190,51 @@ describe("convertFromExpr with a column condition", () => {},]);});+ test("carries shared conditions into nested OR branches", () => {+ expect(+ databaseResources(+ and(+ timeBefore("2026-10-01T00:00:00Z"),+ or(+ columnIn("a"),+ and(+ eq("instance_id", "mysql-instance"),+ eq("database_name", "bytebase_210"),+ eq("column_name", "c")+ )+ )+ )+ )+ ).toEqual([+ { databaseFullName: "", columns: ["a"] },+ {+ databaseFullName: "instances/mysql-instance/databases/bytebase_210",+ instanceResourceId: "mysql-instance",+ databaseResourceId: "bytebase_210",+ columns: ["c"],+ },+ ]);+ });++ test("keeps a broad OR branch broad when another branch names columns", () => {+ expect(+ databaseResources(+ or(eq("database", A), and(eq("database", A), eq("column_name", "c")))+ )+ ).toEqual([{ databaseFullName: A }]);+ });++ test("falls back to the raw condition for independent OR groups", () => {+ expect(+ convertFromExpr(+ and(+ or(+ eq("database", "instances/i/databases/a"),+ eq("database", "instances/i/databases/b")+ ),+ or(eq("column_name", "email"), eq("column_name", "phone"))+ )+ )+ ).toBeUndefined();+ });});diff --git a/frontend/src/utils/issue/cel.ts b/frontend/src/utils/issue/cel.tsindex 18249b5a4a..1ec3be74b2 100644--- a/frontend/src/utils/issue/cel.ts+++ b/frontend/src/utils/issue/cel.ts@@ -361,12 +361,14 @@ const convertToCELString = (export const batchConvertFromCELString = async (cels: string[]-): Promise<ConditionExpression[]> => {+): Promise<(ConditionExpression | undefined)[]> => {const celExprs = await batchConvertCELStringToParsedExpr(cels);- const resp: ConditionExpression[] = [];+ const resp: (ConditionExpression | undefined)[] = [];for (let i = 0; i < celExprs.length; i++) {- if (cels[i] === "true" || !celExprs[i]) {- resp.push({});+ if (cels[i] === "true") {+ resp.push({ databaseResources: [] });+ } else if (!celExprs[i]) {+ resp.push(undefined);} else {resp.push(convertFromExpr(celExprs[i]));}@@ -388,7 +390,10 @@ export const readableCondition = (expr: Expr | undefined): ConditionExpression =>expr- ? { ...convertFromExpr(expr), environments: provenEnvironments(expr) }+ ? {+ ...(convertFromExpr(expr) ?? {}),+ environments: provenEnvironments(expr),+ }: { databaseResources: [] };export const readableConditionFromCELString = async (@@ -444,11 +449,77 @@ const environmentClauseOf = (expr: Expr): string[] | undefined => {return ids && uniq(ids).map((id) => `${environmentNamePrefix}${id}`);};-const splitTopLevelOr = (expr: SimpleExpr): SimpleExpr[] => {- if (expr.type !== ExprType.ConditionGroup || expr.operator !== "_||_") {+// A time limit only expires the entire condition when it is a top-level+// conjunct. A limit under `||` can be bypassed by another branch.+export const getGuaranteedExpiration = (+ expr: Expr | undefined+): Date | undefined => {+ if (!expr) return undefined;++ const expirations = conjuncts(expr)+ .map((conjunct) => {+ const call = callOf(conjunct);+ if (+ call?.function !== "_<_" ||+ factorNameOf(call.args[0]) !== CEL_ATTRIBUTE_REQUEST_TIME+ ) {+ return undefined;+ }+ const timestamp = callOf(call.args[1]);+ if (timestamp?.function !== "timestamp") {+ return undefined;+ }+ const value = constantStringOf(timestamp.args[0]);+ if (!value) return undefined;+ const expiration = new Date(value);+ return Number.isNaN(expiration.getTime()) ? undefined : expiration;+ })+ .filter((expiration): expiration is Date => expiration !== undefined);++ if (expirations.length === 0) return undefined;+ return new Date(Math.min(...expirations.map((expiration) => +expiration)));+};++const hasOnlyBranches = (+ branches: (SimpleExpr[] | undefined)[]+): branches is SimpleExpr[][] =>+ branches.every((branch) => branch !== undefined);++const splitOrBranches = (expr: SimpleExpr): SimpleExpr[] | undefined => {+ if (expr.type !== ExprType.ConditionGroup) {+ return [expr];+ }+ if (expr.operator === "_||_") {+ const branches = expr.args.map(splitOrBranches);+ return hasOnlyBranches(branches) ? branches.flat() : undefined;+ }++ const branchesByArgument = expr.args.map(splitOrBranches);+ if (!hasOnlyBranches(branchesByArgument)) {+ return undefined;+ }+ const alternativeIndex = branchesByArgument.findIndex(+ (branches) => branches.length > 1+ );+ if (alternativeIndex === -1) {return [expr];}- return expr.args.flatMap(splitTopLevelOr);+ if (branchesByArgument.filter((branches) => branches.length > 1).length > 1) {+ return undefined;+ }++ return branchesByArgument[alternativeIndex].map((branch) => {+ const arguments_ = branchesByArgument.map((branches, index) =>+ index === alternativeIndex ? branch : branches[0]+ );+ return arguments_.length === 1+ ? arguments_[0]+ : {+ type: ExprType.ConditionGroup,+ operator: "_&&_",+ args: arguments_,+ };+ });};const mergeDatabaseResources = (@@ -468,11 +539,10 @@ const mergeDatabaseResources = (merged.set(key, { ...resource, columns: resource.columns?.slice() });continue;}- if (resource.columns) {- existing.columns = uniq([- ...(existing.columns ?? []),- ...resource.columns,- ]);+ if (existing.columns === undefined || resource.columns === undefined) {+ existing.columns = undefined;+ } else {+ existing.columns = uniq([...existing.columns, ...resource.columns]);}}return [...merged.values()];@@ -631,8 +701,15 @@ const convertFromSimpleExpr = (simpleExpr: SimpleExpr): ConditionExpression => {return conditionExpression;};-export const convertFromExpr = (expr: Expr): ConditionExpression => {- const branches = splitTopLevelOr(resolveCELExpr(expr));+export const convertFromExpr = (+ expr: Expr+): ConditionExpression | undefined => {+ const branches = splitOrBranches(resolveCELExpr(expr));+ // Resource summaries model one disjunction with shared conditions. Keep+ // CEL with multiple independent disjunctions raw instead of changing it.+ if (!branches) {+ return undefined;+ }if (branches.length === 1) {return convertFromSimpleExpr(branches[0]);}diff --git a/frontend/src/utils/v1/iam.test.ts b/frontend/src/utils/v1/iam.test.tsindex e9498f847f..c2beb750f2 100644--- a/frontend/src/utils/v1/iam.test.ts+++ b/frontend/src/utils/v1/iam.test.ts@@ -10,6 +10,7 @@ import {bindingScopesResources,convertFullnameToMember,convertMemberToFullname,+ isBindingPolicyExpired,} from "./iam";const binding = (expression?: string, parsedExpr?: Expr) =>@@ -28,6 +29,21 @@ const call = (fn: string, args: Expr[]) =>create(ExprSchema, {exprKind: { case: "callExpr", value: { function: fn, args } },});+const string = (value: string) =>+ create(ExprSchema, {+ exprKind: {+ case: "constExpr",+ value: { constantKind: { case: "stringValue", value } },+ },+ });+const resource = (field: string) => select(ident("resource"), field);+const eq = (field: string, value: string) =>+ call("_==_", [resource(field), string(value)]);+const timeBefore = (value: string) =>+ call("_<_", [+ select(ident("request"), "time"),+ call("timestamp", [string(value)]),+ ]);// Mirrors the server's rule: any condition attribute other than request.time// scopes the binding away from project-wide surfaces.@@ -94,6 +110,21 @@ describe("bindingScopesResources", () => {});});+describe("isBindingPolicyExpired", () => {+ test("keeps checking expiry when resource branches cannot be summarized", () => {+ const expr = call("_&&_", [+ call("_||_", [+ eq("database", "instances/i/databases/a"),+ eq("database", "instances/i/databases/b"),+ ]),+ call("_||_", [eq("schema_name", "public"), eq("schema_name", "audit")]),+ timeBefore("2020-01-01T00:00:00Z"),+ ]);++ expect(isBindingPolicyExpired(binding(undefined, expr))).toBe(true);+ });+});+describe("member fullname conversion", () => {test("round-trips supported IAM member identifiers", () => {const members = [diff --git a/frontend/src/utils/v1/iam.ts b/frontend/src/utils/v1/iam.tsindex 9bbd3a0555..41463bf25b 100644--- a/frontend/src/utils/v1/iam.ts+++ b/frontend/src/utils/v1/iam.ts@@ -34,7 +34,7 @@ import type { Binding, IamPolicy } from "@/types/proto-es/v1/iam_policy_pb";import type { Project } from "@/types/proto-es/v1/project_service_pb";import type { User } from "@/types/proto-es/v1/user_service_pb";import { appStoreUtilBridge } from "@/utils/app-store-bridge";-import { convertFromExpr } from "@/utils/issue/cel";+import { convertFromExpr, getGuaranteedExpiration } from "@/utils/issue/cel";import { ensureUserFullName } from "@/utils/v1/user";// expressionReferencesResources walks a parsed CEL condition for any@@ -104,16 +104,8 @@ export const bindingScopesResources = (binding: Binding): boolean => {};export const isBindingPolicyExpired = (binding: Binding): boolean => {- if (binding.parsedExpr) {- const conditionExpr = convertFromExpr(binding.parsedExpr);- if (conditionExpr.expiredTime) {- const expiration = new Date(conditionExpr.expiredTime);- if (expiration < new Date()) {- return true;- }- }- }- return false;+ const expiration = getGuaranteedExpiration(binding.parsedExpr);+ return expiration !== undefined && expiration < new Date();};// Revoke a single member from one specific role binding, returning a new policy@@ -356,6 +348,9 @@ export const checkQuerierPermission = (return true;}const conditionExpr = convertFromExpr(expr);+ if (!conditionExpr) {+ return false;+ }if (conditionExpr.expiredTime &&new Date(conditionExpr.expiredTime).getTime() < Date.now()