Skip to content

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

feat(frontend): migrate database catalog panel to react (#19983)

p0ny2d7592a910c3
diff --git a/docs/superpowers/plans/2026-04-13-project-database-detail-catalog-react-parity.md b/docs/superpowers/plans/2026-04-13-project-database-detail-catalog-react-parity.md
new file mode 100644
index 0000000000..b99a26a0a7
--- /dev/null
+++ b/docs/superpowers/plans/2026-04-13-project-database-detail-catalog-react-parity.md
@@ -0,0 +1,250 @@
+# Project Database Detail Catalog React Parity Implementation Plan
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** Remove the Vue bridge from the project database detail catalog tab and restore full catalog parity with a React-native implementation built from the repo's shadcn-style React primitives.
+
+**Architecture:** Reintroduce a React-owned `DatabaseCatalogPanel` that orchestrates catalog flattening, permissions, feature gating, row selection, inline edits, delete cleanup, and grant-access dialog state. Keep the UI split into a page-specific panel shell, a presentational `SensitiveColumnTable`, and a focused `GrantAccessDialog`, all backed by existing Vue/Pinia stores through `useVueState`.
+
+**Tech Stack:** React, TypeScript, `useVueState`, Pinia stores, protobuf-generated types, shadcn-style UI components on `@base-ui/react`, Tailwind CSS v4, Vitest
+
+---
+
+### Task 1: Restore the React catalog panel shell
+
+**Files:**
+- Modify: `frontend/src/react/pages/project/database-detail/panels/DatabaseCatalogPanel.tsx`
+- Reference: `frontend/src/components/Database/DatabaseSensitiveDataPanel.vue`
+- Reference: `frontend/src/components/SensitiveData/types.ts`
+- Reference: `frontend/src/components/SensitiveData/utils.ts`
+
+- [ ] **Step 1: Replace the Vue bridge with a React implementation**
+
+Rework `DatabaseCatalogPanel.tsx` so it no longer imports `createApp`, `NConfigProvider`, `OverlayStackManager`, or `DatabaseSensitiveDataPanel.vue`. Use the earlier React panel from commit `79dd009d2c` as the behavioral baseline, but keep the current branch's import style and file structure.
+
+The panel should own:
+
+- catalog reads via `useDatabaseCatalog(database.name, false)`
+- reactive store reads via `useVueState`
+- flattening of relational columns, object-schema fields, and table classifications into `MaskData[]`
+- local state for search text, checked rows, feature dialog, and grant-access dialog
+- permission checks for catalog updates and masking exemption creation
+- setting fetches for semantic types and data classification
+- handlers for semantic type edits, classification edits, delete cleanup, and grant-access flow opening
+
+Keep the helper logic inside this file unless a helper becomes reused by both tests and the table component.
+
+- [ ] **Step 2: Preserve the current mutation semantics**
+
+Implement the same write paths used by the Vue panel:
+
+- semantic type changes mutate the row target and persist with `updateDatabaseCatalog`
+- classification changes mutate the row target and persist with `updateDatabaseCatalog`
+- delete clears semantic type and/or classification, persists the catalog, removes the row from the local checked selection, then removes matching masking exemptions from the project policy
+- grant access opens the React dialog only when rows are selected and permissions/feature gates allow it
+
+Continue using:
+
+- `useDatabaseCatalogV1Store()`
+- `usePolicyV1Store()`
+- `useSettingV1Store()`
+- `featureToRef(PlanFeature.FEATURE_DATA_MASKING)`
+- `instanceV1MaskingForNoSQL(...)`
+
+- [ ] **Step 3: Keep parity for NoSQL and feature gating**
+
+Carry forward the Vue panel's NoSQL branching:
+
+- object-schema flattening must still surface nested fields
+- row selection must be disabled when `instanceV1MaskingForNoSQL(...)` says bulk grant access is unavailable
+- rows with unsupported semantic type or classification targets must stay read-only
+- missing masking subscription should open the feature dialog instead of the grant-access dialog
+
+- [ ] **Step 4: Run focused type-check for the panel**
+
+Run:
+
+```bash
+pnpm --dir frontend type-check
+```
+
+- [ ] **Step 5: Commit**
+
+```bash
+git add frontend/src/react/pages/project/database-detail/panels/DatabaseCatalogPanel.tsx
+git commit -m "feat(frontend): restore react database catalog panel"
+```
+
+---
+
+### Task 2: Recreate the catalog UI components with shadcn-style primitives
+
+**Files:**
+- Create: `frontend/src/react/pages/project/database-detail/catalog/SensitiveColumnTable.tsx`
+- Create: `frontend/src/react/pages/project/database-detail/catalog/GrantAccessDialog.tsx`
+- Reference: `frontend/src/components/SensitiveData/components/SensitiveColumnTable.vue`
+- Reference: `frontend/src/components/SensitiveData/exemptionDataUtils.ts`
+- Reference: `frontend/src/components/SensitiveData/utils.ts`
+
+- [ ] **Step 1: Create `SensitiveColumnTable.tsx`**
+
+Port the old React `SensitiveColumnTable` back into the tree, but align it with the repo's current React UI conventions instead of copying raw markup unchanged.
+
+Requirements:
+
+- use the shared React `Table` primitives if they fit cleanly; otherwise keep a narrow custom table wrapper only for what the shared table cannot express
+- use existing `Button` and `Select` components
+- preserve checkbox row selection, inline semantic type editing, inline classification editing, remove action, and empty state
+- show schema-qualified table names and `-` placeholders consistently with the Vue panel
+- avoid Naive UI and Vue cell components
+
+Keep the component presentational:
+
+- no direct store calls
+- all mutations bubble up through callbacks
+- selected rows are controlled by props
+
+- [ ] **Step 2: Create `GrantAccessDialog.tsx`**
+
+Restore the earlier React grant-access dialog and keep its policy-writing logic intact.
+
+Requirements:
+
+- preview selected database resources
+- capture reason, expiration, and members
+- generate the masking exemption expression with `rewriteResourceDatabase(...)`
+- append the new exemption to the existing project masking exemption policy
+- use the project's dialog, input, button, and form-layout patterns
+
+Do not reintroduce the Vue drawer or a bridge wrapper.
+
+- [ ] **Step 3: Wire both components into the panel**
+
+Update `DatabaseCatalogPanel.tsx` to use the new components and verify:
+
+- `SensitiveColumnTable` receives checked rows, filtered rows, option lists, and callbacks
+- `GrantAccessDialog` receives the selected rows converted to the `SensitiveColumn` shape expected by the shared utilities
+- closing the dialog clears checked rows only when the current Vue behavior does so
+
+- [ ] **Step 4: Run fixers and type-check**
+
+Run:
+
+```bash
+pnpm --dir frontend fix
+pnpm --dir frontend type-check
+```
+
+- [ ] **Step 5: Commit**
+
+```bash
+git add frontend/src/react/pages/project/database-detail/catalog/SensitiveColumnTable.tsx frontend/src/react/pages/project/database-detail/catalog/GrantAccessDialog.tsx frontend/src/react/pages/project/database-detail/panels/DatabaseCatalogPanel.tsx
+git commit -m "feat(frontend): restore react catalog interactions"
+```
+
+---
+
+### Task 3: Rebuild and expand the React test coverage
+
+**Files:**
+- Create: `frontend/src/react/pages/project/database-detail/panels/DatabaseCatalogPanel.test.tsx`
+- Modify: `frontend/src/react/pages/project/ProjectDatabaseDetailPage.test.tsx`
+
+- [ ] **Step 1: Restore panel-level tests**
+
+Recreate `DatabaseCatalogPanel.test.tsx` using the earlier React test file from commit `79dd009d2c` as the baseline. Mock the same stores and utilities, then keep or add coverage for:
+
+- rendering flattened relational rows
+- selection enabling the grant-access button
+- missing masking feature opening the feature dialog
+- permission inputs passed to the guard
+- deleting a selected row clearing it from the checked selection
+- inline semantic type and classification updates
+- undefined catalog state before the store has loaded
+
+- [ ] **Step 2: Add parity tests that were easy to miss in the old version**
+
+Add explicit tests for:
+
+- NoSQL mode disables row selection and still renders flattened object-schema rows
+- delete path removes matching masking exemptions from the policy store
+- grant-access submit appends to existing exemptions instead of replacing them
+- action controls are disabled or hidden when `bb.databaseCatalogs.update` is missing
+
+These are the most likely parity regressions after restoring older React code.
+
+- [ ] **Step 3: Keep the page-level integration test minimal**
+
+Do not move detailed workflow assertions into `ProjectDatabaseDetailPage.test.tsx`. Keep that file focused on:
+
+- tab routing
+- permission guard behavior for the catalog tab
+- rendering the catalog panel when the tab is selected
+
+Only update it if the import path, test id expectations, or mounting assumptions change.
+
+- [ ] **Step 4: Run the targeted tests**
+
+Run:
+
+```bash
+pnpm --dir frontend test -- --run frontend/src/react/pages/project/database-detail/panels/DatabaseCatalogPanel.test.tsx frontend/src/react/pages/project/ProjectDatabaseDetailPage.test.tsx
+```
+
+- [ ] **Step 5: Commit**
+
+```bash
+git add frontend/src/react/pages/project/database-detail/panels/DatabaseCatalogPanel.test.tsx frontend/src/react/pages/project/ProjectDatabaseDetailPage.test.tsx
+git commit -m "test(frontend): cover react database catalog parity"
+```
+
+---
+
+### Task 4: Verify, remove bridge assumptions, and finish
+
+**Files:**
+- Modify: `frontend/src/react/pages/project/database-detail/panels/DatabaseCatalogPanel.tsx`
+- Modify: `frontend/src/react/pages/project/database-detail/catalog/SensitiveColumnTable.tsx`
+- Modify: `frontend/src/react/pages/project/database-detail/catalog/GrantAccessDialog.tsx`
+- Modify: `frontend/src/react/pages/project/database-detail/panels/DatabaseCatalogPanel.test.tsx`
+
+- [ ] **Step 1: Remove all page-local Vue bridge dependencies**
+
+Confirm the final catalog implementation no longer imports or depends on:
+
+- `createApp`
+- `NConfigProvider`
+- `themeOverrides`
+- `OverlayStackManager.vue`
+- `DatabaseSensitiveDataPanel.vue`
+- `NaiveUI`
+
+The catalog tab should now be fully React-owned even though it still reads from Vue-backed stores.
+
+- [ ] **Step 2: Run full frontend verification**
+
+Run:
+
+```bash
+pnpm --dir frontend fix
+pnpm --dir frontend check
+pnpm --dir frontend type-check
+pnpm --dir frontend test -- --run frontend/src/react/pages/project/database-detail/panels/DatabaseCatalogPanel.test.tsx frontend/src/react/pages/project/ProjectDatabaseDetailPage.test.tsx
+```
+
+- [ ] **Step 3: Sanity-check the diff**
+
+Run:
+
+```bash
+git diff -- frontend/src/react/pages/project/database-detail/panels/DatabaseCatalogPanel.tsx frontend/src/react/pages/project/database-detail/catalog/SensitiveColumnTable.tsx frontend/src/react/pages/project/database-detail/catalog/GrantAccessDialog.tsx frontend/src/react/pages/project/database-detail/panels/DatabaseCatalogPanel.test.tsx frontend/src/react/pages/project/ProjectDatabaseDetailPage.test.tsx
+```
+
+Verify the final diff shows a React-native catalog flow and no accidental changes outside the catalog scope.
+
+- [ ] **Step 4: Commit final polish**
+
+```bash
+git add frontend/src/react/pages/project/database-detail/panels/DatabaseCatalogPanel.tsx frontend/src/react/pages/project/database-detail/catalog/SensitiveColumnTable.tsx frontend/src/react/pages/project/database-detail/catalog/GrantAccessDialog.tsx frontend/src/react/pages/project/database-detail/panels/DatabaseCatalogPanel.test.tsx frontend/src/react/pages/project/ProjectDatabaseDetailPage.test.tsx
+git commit -m "fix(frontend): finish react database catalog parity"
+```
diff --git a/docs/superpowers/specs/2026-04-13-project-database-detail-catalog-react-parity-design.md b/docs/superpowers/specs/2026-04-13-project-database-detail-catalog-react-parity-design.md
new file mode 100644
index 0000000000..3bfe086dfa
--- /dev/null
+++ b/docs/superpowers/specs/2026-04-13-project-database-detail-catalog-react-parity-design.md
@@ -0,0 +1,199 @@
+# Project Database Detail Catalog React Parity Design
+
+## Summary
+
+Remove the Vue bridge from the project database detail page's catalog tab and replace it with a fully React-owned implementation that preserves the current catalog workflow.
+
+The finished state must not mount `frontend/src/components/Database/DatabaseSensitiveDataPanel.vue` from React. React should own the panel, table interactions, dialogs, and state orchestration while continuing to use the existing shared stores and protobuf types.
+
+## Goals
+
+- Remove the `createApp(...)` bridge in `frontend/src/react/pages/project/database-detail/panels/DatabaseCatalogPanel.tsx`.
+- Keep feature parity with the current Vue-backed catalog panel on the project database detail page.
+- Preserve existing permission, feature-gating, and policy-update behavior.
+- Keep the page route, hash tab behavior, and surrounding React page shell unchanged.
+- Reuse existing store modules and shared sensitive-data utilities instead of inventing a parallel data layer.
+- Use the repo's existing React UI system: shadcn-style components built on `@base-ui/react` and Tailwind v4 tokens.
+
+## Non-Goals
+
+- Do not migrate unrelated database detail tabs.
+- Do not rewrite Vue stores or policy services into React-only state.
+- Do not broaden this work into a generic React replacement for every sensitive-data surface in the app.
+- Do not redesign the catalog workflow.
+
+## Current State
+
+The catalog tab in `frontend/src/react/pages/project/ProjectDatabaseDetailPage.tsx` renders `DatabaseCatalogPanel`, but that component currently mounts a separate Vue app:
+
+- `frontend/src/react/pages/project/database-detail/panels/DatabaseCatalogPanel.tsx`
+- mounts `frontend/src/components/Database/DatabaseSensitiveDataPanel.vue`
+- wraps it in `NConfigProvider` and `OverlayStackManager`
+
+That bridge keeps the route shell in React but leaves the catalog workflow owned by Vue. It carries the same integration risks seen elsewhere in the migration:
+
+- duplicated provider trees
+- bridge-only lifecycle management
+- stale props risk on database navigation
+- reduced React test coverage for the actual workflow
+
+Recent history shows this page already had a React-native catalog implementation and later regressed to the Vue bridge to restore parity quickly. That earlier React implementation is useful source material, but it needs to be treated as a baseline to restore and harden rather than copied blindly.
+
+## Required Parity
+
+The React catalog panel must preserve all of these user-facing behaviors from `frontend/src/components/Database/DatabaseSensitiveDataPanel.vue`:
+
+- feature attention banner for masking
+- search/filter across schema, table, and column names
+- row selection for bulk grant access
+- grant-access button gating based on permissions and subscription state
+- feature paywall dialog when masking is unavailable
+- inline semantic type editing where catalog update is allowed
+- inline classification editing where catalog update is allowed
+- deletion/removal of sensitive markings
+- masking exemption cleanup when a sensitive entry is removed
+- NoSQL-specific behavior differences, especially around row selection and editing
+- i18n-backed display strings only
+
+## Architecture
+
+The catalog migration should stay split into three React units:
+
+### 1. `DatabaseCatalogPanel.tsx`
+
+This is the orchestration layer for the catalog tab.
+
+Responsibilities:
+
+- read the database catalog through the existing store APIs
+- flatten catalog data into table rows
+- own local UI state:
+ - search text
+ - checked rows
+ - feature dialog open state
+ - grant-access dialog open state
+- fetch and read semantic type and data classification settings
+- evaluate permission and feature gates
+- apply mutations for:
+ - semantic type changes
+ - classification changes
+ - removal of sensitive markings
+ - masking exemption cleanup
+
+This component should remain page-specific. It does not need to become a shared sensitive-data framework.
+
+### 2. `catalog/SensitiveColumnTable.tsx`
+
+This is the presentational table for the flattened sensitive-data rows.
+
+Responsibilities:
+
+- render the rows
+- render selection controls when row selection is enabled
+- render inline semantic type and classification controls
+- render remove actions
+- render empty state
+- emit callbacks for edits, delete, and selection changes
+
+The table should be React-native and should not depend on Naive UI or Vue cells. It should be composed from the existing React UI primitives already used elsewhere in this migration, such as the shared `Table`, `Button`, `Select`, `Badge`, and empty-state patterns, rather than bespoke styled markup. It may keep a simpler internal structure than the Vue `NDataTable` implementation as long as behavior parity is preserved.
+
+### 3. `catalog/GrantAccessDialog.tsx`
+
+This owns the masking exemption creation flow for the selected rows.
+
+Responsibilities:
+
+- preview selected database resources
+- collect reason, expiration, and members
+- build the masking exemption expression
+- upsert the project masking exemption policy
+- report success/failure and dismiss cleanly
+
+This dialog can reuse the earlier React implementation structure because it is already close to the existing Vue behavior and has a clear boundary. The form layout should follow the project's shadcn-style composition patterns instead of ad hoc spacing wrappers where practical.
+
+## Data Flow
+
+The React panel should continue to use the existing shared data sources rather than introducing a new fetch layer:
+
+- `useDatabaseCatalog(database.name, false)`
+- `useDatabaseCatalogV1Store()`
+- `usePolicyV1Store()`
+- `useSettingV1Store()`
+- `featureToRef(...)`
+- `useVueState(...)` for reactive store reads
+
+The panel should derive a flattened row list from the database catalog:
+
+- relational table columns with semantic type/classification
+- object-schema leaves for NoSQL/object-based catalogs
+- table-level classifications
+
+That flattening logic should live in React-side helpers close to the panel so the display model is explicit and testable.
+
+## Mutation Rules
+
+The React implementation must preserve the current write semantics:
+
+- semantic type changes mutate the selected target and persist through `updateDatabaseCatalog`
+- classification changes mutate the selected target and persist through `updateDatabaseCatalog`
+- removing a sensitive entry clears semantic type and/or classification on the target, persists the catalog update, then removes matching masking exemptions from the project policy
+- grant access appends new exemptions to the project masking exemption policy rather than replacing unrelated entries
+
+The plan should explicitly test these mutation paths, because this is where parity regressions are most likely.
+
+## NoSQL Handling
+
+The Vue implementation has special handling for NoSQL instances and object-schema catalogs. The React version must keep those branch behaviors:
+
+- detect NoSQL masking mode with `instanceV1MaskingForNoSQL(...)`
+- disable row selection when bulk grant access should not be available
+- preserve object-schema flattening for nested fields
+- prevent unsupported classification or semantic-type edits on targets that do not support them
+
+This is a required part of parity, not a follow-up enhancement.
+
+## File Plan
+
+Primary files to modify or restore:
+
+- `frontend/src/react/pages/project/database-detail/panels/DatabaseCatalogPanel.tsx`
+- `frontend/src/react/pages/project/database-detail/panels/DatabaseCatalogPanel.test.tsx`
+- `frontend/src/react/pages/project/database-detail/catalog/SensitiveColumnTable.tsx`
+- `frontend/src/react/pages/project/database-detail/catalog/GrantAccessDialog.tsx`
+
+Reference files to verify behavior against:
+
+- `frontend/src/components/Database/DatabaseSensitiveDataPanel.vue`
+- `frontend/src/components/SensitiveData/components/SensitiveColumnTable.vue`
+- `frontend/src/components/SensitiveData/types.ts`
+- `frontend/src/components/SensitiveData/utils.ts`
+- `frontend/src/components/SensitiveData/exemptionDataUtils.ts`
+
+## Testing Strategy
+
+The React migration should be validated with focused React tests rather than relying on the page shell test alone.
+
+Minimum coverage:
+
+- panel renders flattened rows from catalog data
+- search filters by schema/table/column
+- missing masking feature opens the feature dialog instead of the grant-access flow
+- row selection enables and clears grant-access state correctly
+- semantic type edit persists catalog updates
+- classification edit persists catalog updates
+- delete clears catalog data and removes masking exemptions
+- NoSQL mode disables selection and preserves object-schema rows
+- permission gating disables or hides actions as expected
+
+The existing page-level test in `frontend/src/react/pages/project/ProjectDatabaseDetailPage.test.tsx` should continue to verify that the catalog tab is routed and permission-guarded correctly, but the detailed workflow tests belong in the panel test file.
+
+## Risks
+
+- The old React implementation may be functionally close but visually or behaviorally behind the current Vue panel in small ways.
+- Inline editing and delete cleanup can regress silently if tests only assert rendered text.
+- Classification and semantic type settings are loaded through Vue-backed stores, so tests need to mock those stores carefully.
+- NoSQL behavior is easy to miss if tests only cover relational catalogs.
+
+## Recommendation
+
+Restore the previous React catalog implementation as the starting point, then reconcile it against the current Vue behavior and today's shared UI patterns. This is the fastest route to a bridge-free panel without accepting a greenfield rewrite's regression risk.
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index ab7f36b809..1c84a0edf9 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -1224,6 +1224,7 @@
"role-grant": {
"all-databases": "All",
"all-databases-tip": "All current and future databases in this project.",
+ "column-scope-select-disabled": "Manually select is unavailable for column-scoped selections.",
"custom-date": "Custom date",
"custom-date-placeholder": "Select expiration date and time",
"details": "Request Details",
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index 46e7e2fcd0..16e04d0890 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -1224,6 +1224,7 @@
"role-grant": {
"all-databases": "todas las bases de datos",
"all-databases-tip": "Todas las bases de datos actuales y futuras de este proyecto.",
+ "column-scope-select-disabled": "La selección manual no está disponible para selecciones con alcance de columna.",
"custom-date": "Fecha personalizada",
"custom-date-placeholder": "Seleccione la fecha y hora de vencimiento",
"details": "Detalles de la solicitud",
diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.json
index 061a6dac8d..a09925cd24 100644
--- a/frontend/src/locales/ja-JP.json
+++ b/frontend/src/locales/ja-JP.json
@@ -1224,6 +1224,7 @@
"role-grant": {
"all-databases": "すべてのデータベース",
"all-databases-tip": "このプロジェクトに属する現在および将来のすべてのデータベース。",
+ "column-scope-select-disabled": "列単位の選択では手動選択を使用できません。",
"custom-date": "カスタム日付",
"custom-date-placeholder": "有効期限と時刻を選択します",
"details": "リクエストの詳細",
diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.json
index ae7425172d..4e5581672d 100644
--- a/frontend/src/locales/vi-VN.json
+++ b/frontend/src/locales/vi-VN.json
@@ -1224,6 +1224,7 @@
"role-grant": {
"all-databases": "Tất cả",
"all-databases-tip": "Tất cả cơ sở dữ liệu hiện tại và tương lai trong dự án này.",
+ "column-scope-select-disabled": "Không thể chọn thủ công cho phạm vi ở mức cột.",
"custom-date": "Ngày tùy chỉnh",
"custom-date-placeholder": "Chọn ngày và giờ hết hạn",
"details": "Yêu cầu chi tiết",
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index 1bf97ad3a9..f48e354a42 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -1224,6 +1224,7 @@
"role-grant": {
"all-databases": "所有数据库",
"all-databases-tip": "所有当前和未来属于这个项目的数据库。",
+ "column-scope-select-disabled": "列级范围的选择不能使用手动选择。",
"custom-date": "自定义日期",
"custom-date-placeholder": "选择到期日期和时间",
"details": "请求详细",
diff --git a/frontend/src/plugins/i18n.test.ts b/frontend/src/plugins/i18n.test.ts
index bbd241b2e3..a01c3ab4f8 100644
--- a/frontend/src/plugins/i18n.test.ts
+++ b/frontend/src/plugins/i18n.test.ts
@@ -169,6 +169,18 @@ const checkKeysSorted = (
return errors;
};
+const getNestedValue = (
+ obj: Record<string, unknown>,
+ path: string
+): unknown => {
+ return path.split(".").reduce<unknown>((current, key) => {
+ if (!current || typeof current !== "object") {
+ return undefined;
+ }
+ return (current as Record<string, unknown>)[key];
+ }, obj);
+};
+
describe("Locale keys are sorted alphabetically", () => {
const localesDirs = [
resolve(__dirname, "../locales"),
@@ -187,6 +199,29 @@ describe("Locale keys are sorted alphabetically", () => {
}
});
+describe("Grant access locale coverage", () => {
+ const localesDirs = [
+ resolve(__dirname, "../locales"),
+ resolve(__dirname, "../react/locales"),
+ ];
+ const requiredKeys = ["issue.role-grant.column-scope-select-disabled"];
+
+ for (const dir of localesDirs) {
+ const files = readdirSync(dir).filter((f) => f.endsWith(".json"));
+ for (const file of files) {
+ const content = JSON.parse(readFileSync(resolve(dir, file), "utf-8"));
+ for (const key of requiredKeys) {
+ test(`${dir.includes("react") ? "react/" : ""}locales/${file} includes ${key}`, () => {
+ expect(
+ getNestedValue(content, key),
+ `${file} missing ${key}`
+ ).toBeTruthy();
+ });
+ }
+ }
+ }
+});
+
const compareMessages = (
localA: LocaleMessageObject,
localB: LocaleMessageObject
diff --git a/frontend/src/react/locales/en-US.json b/frontend/src/react/locales/en-US.json
index ce5e939894..d32fd6a62a 100644
--- a/frontend/src/react/locales/en-US.json
+++ b/frontend/src/react/locales/en-US.json
@@ -369,6 +369,7 @@
"common.no-data": "No data",
"common.only-creator-allowed-export": "Only the creator is allowed to export",
"common.open": "Open",
+ "common.operation": "Operation",
"common.optional": "Optional",
"common.or": "or",
"common.overview": "Overview",
@@ -626,6 +627,7 @@
"unmatched-database": "Unmatched database"
},
"database.classification.self": "Classification",
+ "database.column": "Column",
"database.engine": "Engine",
"database.export-schema": "Export Schema",
"database.export-schema-multi-file": "Multi-File (ZIP)",
@@ -1151,6 +1153,7 @@
"role-grant": {
"all-databases": "All databases",
"all-databases-tip": "All current and future databases in this project.",
+ "column-scope-select-disabled": "Manually select is unavailable for column-scoped selections.",
"details": "Role Grant Details",
"expired-at": "Expired at",
"manually-select": "Manually select",
@@ -1921,7 +1924,9 @@
},
"re-order": "Re-order"
},
+ "grant-access": "Grant Access",
"never-expires": "Never expires",
+ "remove-sensitive-column-tips": "Expose this column?",
"semantic-types": {
"label": "Columns having the same semantic type will use the same masking algorithms.",
"select": "Select semantic type",
diff --git a/frontend/src/react/locales/es-ES.json b/frontend/src/react/locales/es-ES.json
index 851e19027d..3ffe513b93 100644
--- a/frontend/src/react/locales/es-ES.json
+++ b/frontend/src/react/locales/es-ES.json
@@ -369,6 +369,7 @@
"common.no-data": "Sin datos",
"common.only-creator-allowed-export": "Only the creator is allowed to export",
"common.open": "Abrir",
+ "common.operation": "Operación",
"common.optional": "Opcional",
"common.or": "o",
"common.overview": "Resumen",
@@ -626,6 +627,7 @@
"unmatched-database": "Unmatched database"
},
"database.classification.self": "Clasificación",
+ "database.column": "Columna",
"database.engine": "Motor",
"database.export-schema": "Exportar esquema",
"database.export-schema-multi-file": "Multi-archivo (ZIP)",
@@ -1151,6 +1153,7 @@
"role-grant": {
"all-databases": "todas las bases de datos",
"all-databases-tip": "Todas las bases de datos actuales y futuras de este proyecto.",
+ "column-scope-select-disabled": "La selección manual no está disponible para selecciones con alcance de columna.",
"details": "Role Grant Details",
"expired-at": "Expired at",
"manually-select": "selección manual",
@@ -1921,7 +1924,9 @@
},
"re-order": "Reordenar"
},
+ "grant-access": "Conceder acceso",
"never-expires": "Nunca expira",
+ "remove-sensitive-column-tips": "¿Exponer esta columna?",
"semantic-types": {
"label": "Las columnas que tengan el mismo tipo semántico utilizarán los mismos algoritmos de enmascaramiento.",
"select": "Seleccionar tipo semántico",
diff --git a/frontend/src/react/locales/ja-JP.json b/frontend/src/react/locales/ja-JP.json
index 666fcf0c79..d573eb248b 100644
--- a/frontend/src/react/locales/ja-JP.json
+++ b/frontend/src/react/locales/ja-JP.json
@@ -369,6 +369,7 @@
"common.no-data": "データなし",
"common.only-creator-allowed-export": "Only the creator is allowed to export",
"common.open": "開く",
+ "common.operation": "操作",
"common.optional": "オプション",
"common.or": "または",
"common.overview": "概要",
@@ -626,6 +627,7 @@
"unmatched-database": "Unmatched database"
},
"database.classification.self": "分類",
+ "database.column": "列",
"database.engine": "エンジン",
"database.export-schema": "スキーマをエクスポート",
"database.export-schema-multi-file": "複数ファイル (ZIP)",
@@ -1151,6 +1153,7 @@
"role-grant": {
"all-databases": "すべてのデータベース",
"all-databases-tip": "このプロジェクトに属する現在および将来のすべてのデータベース。",
+ "column-scope-select-disabled": "列単位の選択では手動選択を使用できません。",
"details": "Role Grant Details",
"expired-at": "Expired at",
"manually-select": "手動選択",
@@ -1921,7 +1924,9 @@
},
"re-order": "並び替え"
},
+ "grant-access": "アクセスを許可する",
"never-expires": "有効期限なし",
+ "remove-sensitive-column-tips": "このデータ列を表示しますか?",
"semantic-types": {
"label": "同じセマンティック タイプの列は、同じマスキング アルゴリズムを使用します。",
"select": "セマンティックタイプの選択",
diff --git a/frontend/src/react/locales/vi-VN.json b/frontend/src/react/locales/vi-VN.json
index fc8ad7d363..817c070184 100644
--- a/frontend/src/react/locales/vi-VN.json
+++ b/frontend/src/react/locales/vi-VN.json
@@ -369,6 +369,7 @@
"common.no-data": "Không có dữ liệu",
"common.only-creator-allowed-export": "Only the creator is allowed to export",
"common.open": "Mở",
+ "common.operation": "Thao tác",
"common.optional": "Tùy chọn",
"common.or": "hoặc",
"common.overview": "Tổng quan",
@@ -626,6 +627,7 @@
"unmatched-database": "Unmatched database"
},
"database.classification.self": "Phân loại",
+ "database.column": "Cột",
"database.engine": "Engine",
"database.export-schema": "Xuất schema",
"database.export-schema-multi-file": "Nhiều tệp (ZIP)",
@@ -1151,6 +1153,7 @@
"role-grant": {
"all-databases": "Tất cả cơ sở dữ liệu",
"all-databases-tip": "Tất cả cơ sở dữ liệu hiện tại và tương lai trong dự án này.",
+ "column-scope-select-disabled": "Không thể chọn thủ công cho phạm vi ở mức cột.",
"details": "Role Grant Details",
"expired-at": "Expired at",
"manually-select": "Chọn thủ công",
@@ -1921,7 +1924,9 @@
},
"re-order": "Sắp xếp lại"
},
+ "grant-access": "Cấp Quyền truy cập",
"never-expires": "Không bao giờ hết hạn",
+ "remove-sensitive-column-tips": "Hiển thị cột này?",
"semantic-types": {
"label": "Các cột có cùng loại ngữ nghĩa sẽ sử dụng cùng một thuật toán che.",
"select": "Chọn loại ngữ nghĩa",
diff --git a/frontend/src/react/locales/zh-CN.json b/frontend/src/react/locales/zh-CN.json
index 16669340d4..9ae2db1375 100644
--- a/frontend/src/react/locales/zh-CN.json
+++ b/frontend/src/react/locales/zh-CN.json
@@ -369,6 +369,7 @@
"common.no-data": "无数据",
"common.only-creator-allowed-export": "只有创建者可以导出",
"common.open": "打开",
+ "common.operation": "操作",
"common.optional": "可选",
"common.or": "或者",
"common.overview": "概览",
@@ -626,6 +627,7 @@
"unmatched-database": "Unmatched database"
},
"database.classification.self": "分类",
+ "database.column": "列",
"database.engine": "引擎",
"database.export-schema": "导出 Schema",
"database.export-schema-multi-file": "多文件 (ZIP)",
@@ -1151,6 +1153,7 @@
"role-grant": {
"all-databases": "所有数据库",
"all-databases-tip": "所有当前和未来属于这个项目的数据库。",
+ "column-scope-select-disabled": "列级范围的选择不能使用手动选择。",
"details": "Role Grant Details",
"expired-at": "Expired at",
"manually-select": "手动选择",
@@ -1921,7 +1924,9 @@
},
"re-order": "排序"
},
+ "grant-access": "授予访问权限",
"never-expires": "无过期时间",
+ "remove-sensitive-column-tips": "不再对此列数据脱敏?",
"semantic-types": {
"label": "具有相同语义类型的列会使用相同的脱敏算法。",
"select": "选择语义类型",
diff --git a/frontend/src/react/pages/project/ProjectDatabaseDetailPage.test.tsx b/frontend/src/react/pages/project/ProjectDatabaseDetailPage.test.tsx
index 3936b3616f..3234323ac5 100644
--- a/frontend/src/react/pages/project/ProjectDatabaseDetailPage.test.tsx
+++ b/frontend/src/react/pages/project/ProjectDatabaseDetailPage.test.tsx
@@ -318,9 +318,15 @@ vi.mock("@/components/Plan/logic/issue", () => ({
}));
vi.mock("./database-detail/DatabaseDetailActions", () => ({
- DatabaseDetailActions: vi.fn(() => (
- <div data-testid="database-detail-actions" />
- )),
+ DatabaseDetailActions: vi.fn(
+ ({ onOpenTransferProject }: { onOpenTransferProject?: () => void }) => (
+ <div data-testid="database-detail-actions">
+ <button type="button" onClick={onOpenTransferProject}>
+ database.transfer-project
+ </button>
+ </div>
+ )
+ ),
}));
vi.mock("./database-detail/DatabaseDetailHeader", () => ({
diff --git a/frontend/src/react/pages/project/database-detail/catalog/GrantAccessDialog.test.tsx b/frontend/src/react/pages/project/database-detail/catalog/GrantAccessDialog.test.tsx
new file mode 100644
index 0000000000..14a37ead07
--- /dev/null
+++ b/frontend/src/react/pages/project/database-detail/catalog/GrantAccessDialog.test.tsx
@@ -0,0 +1,507 @@
+import type {
+ ButtonHTMLAttributes,
+ InputHTMLAttributes,
+ ReactNode,
+} from "react";
+import { act } from "react";
+import { createRoot } from "react-dom/client";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+import type { SensitiveColumn } from "@/components/SensitiveData/types";
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+const mocks = vi.hoisted(() => {
+ const convertedExpr = {
+ type: "ConditionGroup",
+ operator: "_&&_",
+ args: [
+ {
+ type: "Condition",
+ operator: "_==_",
+ args: ["resource.database", "instances/inst1/databases/db1"],
+ },
+ ],
+ };
+
+ return {
+ convertedExpr,
+ batchConvertCELStringToParsedExpr: vi.fn(async () => [{ parsed: true }]),
+ resolveCELExpr: vi.fn(() => convertedExpr),
+ stringifyConditionExpression: vi.fn(() => "serialized-selection"),
+ featureToRef: vi.fn(() => ({ value: true })),
+ useVueState: vi.fn((getter: () => unknown) => getter()),
+ usePolicyV1Store: vi.fn(() => ({
+ getOrFetchPolicyByParentAndType: vi.fn(),
+ upsertPolicy: vi.fn(),
+ })),
+ };
+});
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({
+ t: (key: string) => key,
+ }),
+}));
+
+vi.mock("@/components/ExprEditor/context", () => ({}));
+
+vi.mock("@/components/SensitiveData/components/utils", () => ({
+ getClassificationLevelOptions: () => [],
+}));
+
+vi.mock("@/components/SensitiveData/exemptionDataUtils", () => ({
+ rewriteResourceDatabase: vi.fn((expression: string) => expression),
+}));
+
+vi.mock("@/components/SensitiveData/utils", () => ({
+ convertSensitiveColumnToDatabaseResource: vi.fn((column) => ({
+ databaseFullName: column.database.name,
+ schema: column.maskData.schema,
+ table: column.maskData.table,
+ columns: [column.maskData.column].filter(Boolean),
+ })),
+ getExpressionsForDatabaseResource: vi.fn(() => []),
+}));
+
+vi.mock("@/plugins/cel", () => ({
+ ExprType: {
+ Condition: "Condition",
+ ConditionGroup: "ConditionGroup",
+ RawString: "RawString",
+ },
+ buildCELExpr: vi.fn(),
+ emptySimpleExpr: vi.fn(() => ({
+ type: "ConditionGroup",
+ operator: "_&&_",
+ args: [],
+ })),
+ isConditionExpr: vi.fn((expr) => expr?.type === "Condition"),
+ isConditionGroupExpr: vi.fn((expr) => expr?.type === "ConditionGroup"),
+ isRawStringExpr: vi.fn((expr) => expr?.type === "RawString"),
+ resolveCELExpr: mocks.resolveCELExpr,
+ validateSimpleExpr: vi.fn(() => true),
+ wrapAsGroup: vi.fn((expr) => expr),
+}));
+
+vi.mock("@/react/components/AccountMultiSelect", () => ({
+ AccountMultiSelect: ({
+ value,
+ onChange,
+ }: {
+ value: string[];
+ onChange: (value: string[]) => void;
+ }) => (
+ <button
+ data-testid="account-multi-select"
+ onClick={() => onChange([...value, "users/alice"])}
+ type="button"
+ />
+ ),
+}));
+
+vi.mock("@/react/components/DatabaseResourceSelector", () => ({
+ DatabaseResourceSelector: ({ value }: { value: unknown }) => (
+ <div data-testid="database-resource-selector">{JSON.stringify(value)}</div>
+ ),
+}));
+
+vi.mock("@/react/components/ExprEditor", () => ({
+ ExprEditor: ({
+ expr,
+ onUpdate,
+ }: {
+ expr: unknown;
+ onUpdate: (expr: unknown) => void;
+ }) => (
+ <div>
+ <div data-testid="expr-editor">{JSON.stringify(expr)}</div>
+ <button
+ data-testid="expr-editor-set-column-scope"
+ onClick={() =>
+ onUpdate({
+ type: "ConditionGroup",
+ operator: "_&&_",
+ args: [
+ {
+ type: "Condition",
+ operator: "_==_",
+ args: ["resource.column_name", "id"],
+ },
+ ],
+ })
+ }
+ type="button"
+ />
+ </div>
+ ),
+}));
+
+vi.mock("@/react/components/FeatureAttention", () => ({
+ FeatureAttention: () => <div data-testid="feature-attention" />,
+}));
+
+vi.mock("@/react/components/FeatureBadge", () => ({
+ FeatureBadge: () => <div data-testid="feature-badge" />,
+}));
+
+vi.mock("@/react/components/ui/button", () => ({
+ Button: (props: ButtonHTMLAttributes<HTMLButtonElement>) => (
+ <button {...props} />
+ ),
+}));
+
+vi.mock("@/react/components/ui/dialog", () => ({
+ Dialog: ({ children, open }: { children: ReactNode; open: boolean }) =>
+ open ? <div>{children}</div> : null,
+ DialogContent: ({ children }: { children: ReactNode }) => (
+ <div>{children}</div>
+ ),
+ DialogTitle: ({ children }: { children: ReactNode }) => <div>{children}</div>,
+}));
+
+vi.mock("@/react/components/ui/expiration-picker", () => ({
+ ExpirationPicker: ({ minDate }: { minDate: string }) => (
+ <div data-min-date={minDate} data-testid="expiration-picker" />
+ ),
+}));
+
+vi.mock("@/react/components/ui/input", () => ({
+ Input: (props: InputHTMLAttributes<HTMLInputElement>) => <input {...props} />,
+}));
+
+vi.mock("@/react/components/ui/tooltip", () => ({
+ Tooltip: ({ children }: { children: ReactNode }) => <>{children}</>,
+}));
+
+vi.mock("@/react/hooks/useVueState", () => ({
+ useVueState: mocks.useVueState,
+}));
+
+vi.mock("@/store", () => ({
+ featureToRef: mocks.featureToRef,
+ pushNotification: vi.fn(),
+ usePolicyV1Store: mocks.usePolicyV1Store,
+}));
+
+vi.mock("@/utils", () => ({
+ batchConvertParsedExprToCELString: vi.fn(),
+ getDatabaseNameOptionConfig: vi.fn(() => ({ options: [] })),
+}));
+
+vi.mock("@/utils/issue/cel", () => ({
+ convertFromExpr: vi.fn(() => ({
+ databaseResources: [],
+ })),
+ stringifyConditionExpression: mocks.stringifyConditionExpression,
+}));
+
+vi.mock("@/utils/v1/cel", () => ({
+ batchConvertCELStringToParsedExpr: mocks.batchConvertCELStringToParsedExpr,
+}));
+
+import { GrantAccessDialog } from "./GrantAccessDialog";
+
+const flush = async () => {
+ await act(async () => {
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+};
+
+const deferred = <T,>() => {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((resolver) => {
+ resolve = resolver;
+ });
+ return { promise, resolve };
+};
+
+const click = async (element: HTMLElement) => {
+ act(() => {
+ element.dispatchEvent(
+ new MouseEvent("click", { bubbles: true, cancelable: true })
+ );
+ });
+ await flush();
+};
+
+const changeTextInput = async (input: HTMLInputElement, value: string) => {
+ act(() => {
+ const descriptor = Object.getOwnPropertyDescriptor(
+ HTMLInputElement.prototype,
+ "value"
+ );
+ descriptor?.set?.call(input, value);
+ input.dispatchEvent(new Event("input", { bubbles: true }));
+ input.dispatchEvent(new Event("change", { bubbles: true }));
+ });
+ await flush();
+};
+
+const createColumnList = (): SensitiveColumn[] =>
+ [
+ {
+ database: {
+ name: "instances/inst1/databases/db1",
+ } as SensitiveColumn["database"],
+ maskData: {
+ schema: "public",
+ table: "book",
+ column: "",
+ semanticTypeId: "",
+ classificationId: "",
+ target: {} as SensitiveColumn["maskData"]["target"],
+ } as SensitiveColumn["maskData"],
+ },
+ ] satisfies SensitiveColumn[];
+
+const renderGrantAccessDialog = ({
+ open = true,
+ columnList = createColumnList(),
+}: {
+ open?: boolean;
+ columnList?: SensitiveColumn[];
+} = {}) => {
+ const container = document.createElement("div");
+ const root = createRoot(container);
+
+ const render = (nextOpen = open, nextColumnList = columnList) => {
+ act(() => {
+ root.render(
+ <GrantAccessDialog
+ open={nextOpen}
+ projectName="projects/proj1"
+ columnList={nextColumnList}
+ onDismiss={vi.fn()}
+ />
+ );
+ });
+ };
+
+ render(open);
+
+ return {
+ container,
+ render,
+ unmount: () =>
+ act(() => {
+ root.unmount();
+ }),
+ };
+};
+
+describe("GrantAccessDialog", () => {
+ beforeEach(() => {
+ mocks.batchConvertCELStringToParsedExpr.mockClear();
+ mocks.resolveCELExpr.mockClear();
+ mocks.stringifyConditionExpression.mockClear();
+ });
+
+ test("preserves selected scope when switching from select to expression mode", async () => {
+ const { container, unmount } = renderGrantAccessDialog();
+ await flush();
+
+ const radioList = Array.from(
+ container.querySelectorAll<HTMLInputElement>('input[type="radio"]')
+ );
+
+ expect(radioList).toHaveLength(3);
+ expect(radioList[2]?.checked).toBe(true);
+
+ await click(radioList[1]!);
+
+ expect(mocks.stringifyConditionExpression).toHaveBeenCalledWith({
+ databaseResources: [
+ {
+ columns: [],
+ databaseFullName: "instances/inst1/databases/db1",
+ schema: "public",
+ table: "book",
+ },
+ ],
+ });
+ expect(mocks.batchConvertCELStringToParsedExpr).toHaveBeenCalledWith([
+ "serialized-selection",
+ ]);
+
+ const exprEditor = container.querySelector('[data-testid="expr-editor"]');
+ expect(exprEditor?.textContent).toContain(
+ JSON.stringify(mocks.convertedExpr)
+ );
+
+ unmount();
+ });
+
+ test("falls back to a raw expression when initial CEL conversion fails", async () => {
+ mocks.batchConvertCELStringToParsedExpr.mockImplementationOnce(
+ async () => [undefined] as unknown as [{ parsed: true }]
+ );
+
+ const { container, unmount } = renderGrantAccessDialog({
+ columnList: [
+ {
+ database: {
+ name: "instances/inst1/databases/db1",
+ } as SensitiveColumn["database"],
+ maskData: {
+ schema: "public",
+ table: "book",
+ column: "id",
+ semanticTypeId: "",
+ classificationId: "",
+ target: {} as SensitiveColumn["maskData"]["target"],
+ } as SensitiveColumn["maskData"],
+ },
+ ],
+ });
+ await flush();
+
+ const radioList = Array.from(
+ container.querySelectorAll<HTMLInputElement>('input[type="radio"]')
+ );
+ expect(radioList[1]?.checked).toBe(true);
+ expect(radioList[2]?.disabled).toBe(true);
+
+ const exprEditor = container.querySelector('[data-testid="expr-editor"]');
+ expect(exprEditor?.textContent).toContain("serialized-selection");
+
+ unmount();
+ });
+
+ test("disables select mode after CEL scope becomes column-scoped", async () => {
+ const { container, unmount } = renderGrantAccessDialog();
+ await flush();
+
+ let radioList = Array.from(
+ container.querySelectorAll<HTMLInputElement>('input[type="radio"]')
+ );
+ expect(radioList[2]?.checked).toBe(true);
+ expect(radioList[2]?.disabled).toBe(false);
+
+ await click(radioList[1]!);
+ await click(
+ container.querySelector<HTMLElement>(
+ '[data-testid="expr-editor-set-column-scope"]'
+ )!
+ );
+
+ radioList = Array.from(
+ container.querySelectorAll<HTMLInputElement>('input[type="radio"]')
+ );
+ expect(radioList[1]?.checked).toBe(true);
+ expect(radioList[2]?.disabled).toBe(true);
+
+ await click(radioList[2]!);
+
+ radioList = Array.from(
+ container.querySelectorAll<HTMLInputElement>('input[type="radio"]')
+ );
+ expect(radioList[1]?.checked).toBe(true);
+ expect(container.querySelector('[data-testid="expr-editor"]')).toBeTruthy();
+
+ unmount();
+ });
+
+ test("refreshes the expiration minimum when reopening the dialog", async () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date("2026-04-14T08:00:00Z"));
+
+ const { container, render, unmount } = renderGrantAccessDialog();
+ await flush();
+
+ const initialPicker = container.querySelector(
+ '[data-testid="expiration-picker"]'
+ );
+ expect(initialPicker?.getAttribute("data-min-date")).toBe(
+ "2026-04-14T00:00"
+ );
+
+ vi.setSystemTime(new Date("2026-04-15T08:00:00Z"));
+ render(false);
+ await flush();
+ render(true);
+ await flush();
+
+ const reopenedPicker = container.querySelector(
+ '[data-testid="expiration-picker"]'
+ );
+ expect(reopenedPicker?.getAttribute("data-min-date")).toBe(
+ "2026-04-15T00:00"
+ );
+
+ unmount();
+ vi.useRealTimers();
+ });
+
+ test("keeps the latest mode when an earlier async conversion resolves late", async () => {
+ const pendingConversion = deferred<[{ parsed: true }]>();
+ mocks.batchConvertCELStringToParsedExpr.mockImplementationOnce(
+ () => pendingConversion.promise
+ );
+
+ const { container, unmount } = renderGrantAccessDialog();
+ await flush();
+
+ const radioList = Array.from(
+ container.querySelectorAll<HTMLInputElement>('input[type="radio"]')
+ );
+
+ expect(radioList[2]?.checked).toBe(true);
+
+ act(() => {
+ radioList[1]?.dispatchEvent(
+ new MouseEvent("click", { bubbles: true, cancelable: true })
+ );
+ });
+ await flush();
+
+ act(() => {
+ radioList[0]?.dispatchEvent(
+ new MouseEvent("click", { bubbles: true, cancelable: true })
+ );
+ });
+ await flush();
+
+ pendingConversion.resolve([{ parsed: true }]);
+ await flush();
+
+ const refreshedRadioList = Array.from(
+ container.querySelectorAll<HTMLInputElement>('input[type="radio"]')
+ );
+ expect(refreshedRadioList[0]?.checked).toBe(true);
+ expect(refreshedRadioList[1]?.checked).toBe(false);
+ expect(
+ container.querySelector('[data-testid="expr-editor"]')
+ ).not.toBeTruthy();
+
+ unmount();
+ });
+
+ test("does not reset form state when reopened props are semantically unchanged", async () => {
+ const initialColumnList = createColumnList();
+ const { container, render, unmount } = renderGrantAccessDialog({
+ columnList: initialColumnList,
+ });
+ await flush();
+
+ const descriptionInput = container.querySelector<HTMLInputElement>(
+ 'input[placeholder="common.description"]'
+ );
+ expect(descriptionInput).toBeTruthy();
+
+ await changeTextInput(descriptionInput!, "temporary reason");
+ expect(descriptionInput?.value).toBe("temporary reason");
+
+ render(true, createColumnList());
+ await flush();
+
+ const refreshedDescriptionInput = container.querySelector<HTMLInputElement>(
+ 'input[placeholder="common.description"]'
+ );
+ expect(refreshedDescriptionInput?.value).toBe("temporary reason");
+
+ unmount();
+ });
+});
diff --git a/frontend/src/react/pages/project/database-detail/catalog/GrantAccessDialog.tsx b/frontend/src/react/pages/project/database-detail/catalog/GrantAccessDialog.tsx
new file mode 100644
index 0000000000..f27fb03368
--- /dev/null
+++ b/frontend/src/react/pages/project/database-detail/catalog/GrantAccessDialog.tsx
@@ -0,0 +1,712 @@
+import { create } from "@bufbuild/protobuf";
+import dayjs from "dayjs";
+import { CircleHelp } from "lucide-react";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { type OptionConfig } from "@/components/ExprEditor/context";
+import { getClassificationLevelOptions } from "@/components/SensitiveData/components/utils";
+import { rewriteResourceDatabase } from "@/components/SensitiveData/exemptionDataUtils";
+import type { SensitiveColumn } from "@/components/SensitiveData/types";
+import {
+ convertSensitiveColumnToDatabaseResource,
+ getExpressionsForDatabaseResource as getResourceExpressions,
+} from "@/components/SensitiveData/utils";
+import type {
+ ConditionGroupExpr,
+ Factor,
+ Operator,
+ SimpleExpr,
+} from "@/plugins/cel";
+import {
+ buildCELExpr,
+ ExprType,
+ emptySimpleExpr,
+ isConditionExpr,
+ isConditionGroupExpr,
+ isRawStringExpr,
+ resolveCELExpr,
+ validateSimpleExpr,
+ wrapAsGroup,
+} from "@/plugins/cel";
+import { AccountMultiSelect } from "@/react/components/AccountMultiSelect";
+import { DatabaseResourceSelector } from "@/react/components/DatabaseResourceSelector";
+import { ExprEditor } from "@/react/components/ExprEditor";
+import { FeatureAttention } from "@/react/components/FeatureAttention";
+import { FeatureBadge } from "@/react/components/FeatureBadge";
+import { Button } from "@/react/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogTitle,
+} from "@/react/components/ui/dialog";
+import { ExpirationPicker } from "@/react/components/ui/expiration-picker";
+import { Input } from "@/react/components/ui/input";
+import { Tooltip } from "@/react/components/ui/tooltip";
+import { useVueState } from "@/react/hooks/useVueState";
+import { featureToRef, pushNotification, usePolicyV1Store } from "@/store";
+import type { DatabaseResource } from "@/types";
+import { ExprSchema } from "@/types/proto-es/google/type/expr_pb";
+import type {
+ Instance,
+ InstanceResource,
+} from "@/types/proto-es/v1/instance_service_pb";
+import {
+ MaskingExemptionPolicy_ExemptionSchema,
+ MaskingExemptionPolicySchema,
+ PolicyResourceType,
+ PolicyType,
+} from "@/types/proto-es/v1/org_policy_service_pb";
+import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";
+import {
+ batchConvertParsedExprToCELString,
+ getDatabaseNameOptionConfig,
+} from "@/utils";
+import {
+ CEL_ATTRIBUTE_RESOURCE_CLASSIFICATION_LEVEL,
+ CEL_ATTRIBUTE_RESOURCE_COLUMN_NAME,
+ CEL_ATTRIBUTE_RESOURCE_DATABASE,
+ CEL_ATTRIBUTE_RESOURCE_SCHEMA_NAME,
+ CEL_ATTRIBUTE_RESOURCE_TABLE_NAME,
+} from "@/utils/cel-attributes";
+import {
+ convertFromExpr,
+ stringifyConditionExpression,
+} from "@/utils/issue/cel";
+import { batchConvertCELStringToParsedExpr } from "@/utils/v1/cel";
+
+type RadioValue = "ALL" | "EXPRESSION" | "SELECT";
+
+interface GrantAccessDialogProps {
+ open: boolean;
+ projectName: string;
+ columnList: SensitiveColumn[];
+ instance?: Instance | InstanceResource;
+ onDismiss: () => void;
+}
+
+const hasColumnScopedResources = (resources: DatabaseResource[]): boolean => {
+ return resources.some((resource) => (resource.columns?.length ?? 0) > 0);
+};
+
+const hasColumnScopedExpr = (expr: SimpleExpr): boolean => {
+ if (isConditionGroupExpr(expr)) {
+ return expr.args.some((arg) => hasColumnScopedExpr(arg));
+ }
+ if (isConditionExpr(expr)) {
+ return expr.args[0] === CEL_ATTRIBUTE_RESOURCE_COLUMN_NAME;
+ }
+ if (isRawStringExpr(expr)) {
+ return expr.content.includes(CEL_ATTRIBUTE_RESOURCE_COLUMN_NAME);
+ }
+ return false;
+};
+
+export function GrantAccessDialog({
+ open,
+ projectName,
+ columnList,
+ instance,
+ onDismiss,
+}: GrantAccessDialogProps) {
+ const { t } = useTranslation();
+ const policyStore = usePolicyV1Store();
+
+ const hasRequiredFeature = useVueState(
+ () => featureToRef(PlanFeature.FEATURE_DATA_MASKING, instance).value
+ );
+
+ const initialDatabaseResources = useMemo<DatabaseResource[]>(
+ () => columnList.map(convertSensitiveColumnToDatabaseResource),
+ [columnList]
+ );
+ const hasColumnScopedResource = useMemo(
+ () => hasColumnScopedResources(initialDatabaseResources),
+ [initialDatabaseResources]
+ );
+ const initialDatabaseResourceKey = useMemo(
+ () =>
+ initialDatabaseResources
+ .map((resource) =>
+ [
+ resource.databaseFullName,
+ resource.schema ?? "",
+ resource.table ?? "",
+ (resource.columns ?? []).join(","),
+ ].join("|")
+ )
+ .sort()
+ .join("||"),
+ [initialDatabaseResources]
+ );
+ const [radioValue, setRadioValue] = useState<RadioValue>("ALL");
+ const [databaseResources, setDatabaseResources] = useState<
+ DatabaseResource[]
+ >([]);
+ const [expr, setExpr] = useState<ConditionGroupExpr>(
+ wrapAsGroup(emptySimpleExpr())
+ );
+ const [description, setDescription] = useState("");
+ const [expirationTimestamp, setExpirationTimestamp] = useState<
+ string | undefined
+ >();
+ const [memberList, setMemberList] = useState<string[]>([]);
+ const [processing, setProcessing] = useState(false);
+ const [modeChangeProcessing, setModeChangeProcessing] = useState(false);
+ const [showFeatureModal, setShowFeatureModal] = useState(false);
+ const lastInitializationKeyRef = useRef<string | undefined>(undefined);
+ const modeChangeRequestIdRef = useRef(0);
+
+ const convertToConditionGroupExpr = useCallback(
+ async (resources: DatabaseResource[]) => {
+ if (resources.length === 0) {
+ return wrapAsGroup(emptySimpleExpr());
+ }
+
+ const expression = stringifyConditionExpression({
+ databaseResources: resources,
+ });
+
+ try {
+ const parsedExprs = await batchConvertCELStringToParsedExpr([
+ expression,
+ ]);
+ const parsedExpr = parsedExprs[0];
+ if (parsedExpr) {
+ return wrapAsGroup(resolveCELExpr(parsedExpr));
+ }
+ } catch {
+ // Fall through to a raw string expression so the current scope stays
+ // editable/submittable even if CEL parsing is temporarily unavailable.
+ }
+
+ return wrapAsGroup({
+ type: ExprType.RawString,
+ content: expression,
+ });
+ },
+ []
+ );
+
+ useEffect(() => {
+ if (!open) {
+ return;
+ }
+ if (lastInitializationKeyRef.current === initialDatabaseResourceKey) {
+ return;
+ }
+ lastInitializationKeyRef.current = initialDatabaseResourceKey;
+
+ if (!open) {
+ return;
+ }
+ let cancelled = false;
+ const initialize = async () => {
+ if (cancelled) {
+ return;
+ }
+ setDatabaseResources(initialDatabaseResources);
+ setDescription("");
+ setExpirationTimestamp(undefined);
+ setMemberList([]);
+ setProcessing(false);
+ setShowFeatureModal(false);
+
+ if (initialDatabaseResources.length === 0) {
+ if (cancelled) {
+ return;
+ }
+ setRadioValue("ALL");
+ setExpr(wrapAsGroup(emptySimpleExpr()));
+ return;
+ }
+
+ if (!hasColumnScopedResource) {
+ if (cancelled) {
+ return;
+ }
+ setRadioValue("SELECT");
+ setExpr(wrapAsGroup(emptySimpleExpr()));
+ return;
+ }
+
+ const nextExpr = await convertToConditionGroupExpr(
+ initialDatabaseResources
+ );
+ if (cancelled || !nextExpr) {
+ return;
+ }
+ setExpr(nextExpr);
+ setRadioValue("EXPRESSION");
+ };
+
+ void initialize();
+ return () => {
+ cancelled = true;
+ };
+ }, [
+ open,
+ initialDatabaseResources,
+ initialDatabaseResourceKey,
+ hasColumnScopedResource,
+ convertToConditionGroupExpr,
+ ]);
+
+ useEffect(() => {
+ if (open) {
+ return;
+ }
+ lastInitializationKeyRef.current = undefined;
+ modeChangeRequestIdRef.current += 1;
+ setModeChangeProcessing(false);
+ }, [open]);
+
+ const exprHasColumnScope = useMemo(() => hasColumnScopedExpr(expr), [expr]);
+ const selectModeDisabled = useMemo(() => {
+ if (hasColumnScopedResource) {
+ return true;
+ }
+ if (radioValue === "EXPRESSION") {
+ return exprHasColumnScope;
+ }
+ return false;
+ }, [hasColumnScopedResource, radioValue, exprHasColumnScope]);
+
+ const isValid = useMemo(() => {
+ switch (radioValue) {
+ case "SELECT":
+ return databaseResources.length > 0;
+ case "EXPRESSION":
+ return validateSimpleExpr(expr);
+ default:
+ return true;
+ }
+ }, [radioValue, databaseResources, expr]);
+
+ const submitDisabled = useMemo(
+ () => memberList.length === 0 || !isValid,
+ [memberList, isValid]
+ );
+
+ const factorList = useMemo((): Factor[] => {
+ return [
+ CEL_ATTRIBUTE_RESOURCE_DATABASE,
+ CEL_ATTRIBUTE_RESOURCE_TABLE_NAME,
+ CEL_ATTRIBUTE_RESOURCE_SCHEMA_NAME,
+ CEL_ATTRIBUTE_RESOURCE_COLUMN_NAME,
+ CEL_ATTRIBUTE_RESOURCE_CLASSIFICATION_LEVEL,
+ ];
+ }, []);
+
+ const factorOperatorOverrideMap = useMemo(
+ () =>
+ new Map<Factor, Operator[]>([
+ [CEL_ATTRIBUTE_RESOURCE_DATABASE, ["_==_", "@in"]],
+ [CEL_ATTRIBUTE_RESOURCE_SCHEMA_NAME, ["_==_"]],
+ [CEL_ATTRIBUTE_RESOURCE_TABLE_NAME, ["_==_", "@in"]],
+ [CEL_ATTRIBUTE_RESOURCE_COLUMN_NAME, ["_==_", "@in"]],
+ [
+ CEL_ATTRIBUTE_RESOURCE_CLASSIFICATION_LEVEL,
+ ["_==_", "_!=_", "_<_", "_<=_", "_>=_", "_>_"],
+ ],
+ ]),
+ []
+ );
+
+ const factorOptionConfigMap = useMemo((): Map<Factor, OptionConfig> => {
+ return factorList.reduce((map, factor) => {
+ if (factor === CEL_ATTRIBUTE_RESOURCE_DATABASE) {
+ map.set(factor, getDatabaseNameOptionConfig(projectName));
+ } else if (factor === CEL_ATTRIBUTE_RESOURCE_CLASSIFICATION_LEVEL) {
+ map.set(factor, {
+ options: getClassificationLevelOptions(),
+ });
+ } else {
+ map.set(factor, { options: [] });
+ }
+ return map;
+ }, new Map<Factor, OptionConfig>());
+ }, [factorList, projectName]);
+
+ const minDatetime = dayjs().startOf("day").format("YYYY-MM-DDTHH:mm");
+
+ const convertToDatabaseResources = useCallback(
+ async (expr: ConditionGroupExpr) => {
+ try {
+ const parsedExpr = await buildCELExpr(expr);
+ if (!parsedExpr) {
+ return;
+ }
+ return convertFromExpr(parsedExpr).databaseResources;
+ } catch {
+ return;
+ }
+ },
+ []
+ );
+
+ const onRadioChange = useCallback(
+ async (value: RadioValue) => {
+ if (!hasRequiredFeature && value !== "ALL") {
+ setShowFeatureModal(true);
+ return;
+ }
+ if (value === "SELECT" && selectModeDisabled) {
+ return;
+ }
+
+ const requestId = modeChangeRequestIdRef.current + 1;
+ modeChangeRequestIdRef.current = requestId;
+
+ const requiresConversion =
+ (value === "EXPRESSION" && radioValue === "SELECT") ||
+ (value === "SELECT" && radioValue === "EXPRESSION");
+
+ if (!requiresConversion) {
+ setModeChangeProcessing(false);
+ setRadioValue(value);
+ return;
+ }
+
+ setModeChangeProcessing(true);
+ try {
+ if (value === "EXPRESSION" && radioValue === "SELECT") {
+ const nextExpr = await convertToConditionGroupExpr(databaseResources);
+ if (modeChangeRequestIdRef.current !== requestId) {
+ return;
+ }
+ if (nextExpr) {
+ setExpr(nextExpr);
+ }
+ } else if (value === "SELECT" && radioValue === "EXPRESSION") {
+ const nextResources = await convertToDatabaseResources(expr);
+ if (modeChangeRequestIdRef.current !== requestId) {
+ return;
+ }
+ if (nextResources) {
+ setDatabaseResources(nextResources);
+ }
+ }
+
+ if (modeChangeRequestIdRef.current !== requestId) {
+ return;
+ }
+ setRadioValue(value);
+ } finally {
+ if (modeChangeRequestIdRef.current === requestId) {
+ setModeChangeProcessing(false);
+ }
+ }
+ },
+ [
+ hasRequiredFeature,
+ selectModeDisabled,
+ radioValue,
+ convertToConditionGroupExpr,
+ databaseResources,
+ convertToDatabaseResources,
+ expr,
+ ]
+ );
+
+ const onDismissInternal = useCallback(() => {
+ onDismiss();
+ }, [onDismiss]);
+
+ const onSubmit = useCallback(async () => {
+ if (processing) return;
+ setProcessing(true);
+
+ try {
+ const exemptions = [];
+
+ const extraExpressions: string[] = [];
+ if (expirationTimestamp) {
+ extraExpressions.push(
+ `request.time < timestamp("${new Date(expirationTimestamp).toISOString()}")`
+ );
+ }
+
+ if (radioValue === "EXPRESSION") {
+ const parsedExpr = await buildCELExpr(expr);
+ if (parsedExpr) {
+ let [celString] = await batchConvertParsedExprToCELString([
+ parsedExpr,
+ ]);
+ celString = rewriteResourceDatabase(celString);
+ const parts = [celString, ...extraExpressions].filter((e) => e);
+ exemptions.push(
+ create(MaskingExemptionPolicy_ExemptionSchema, {
+ members: memberList,
+ condition: create(ExprSchema, {
+ description,
+ expression: parts.length > 0 ? parts.join(" && ") : "",
+ }),
+ })
+ );
+ }
+ } else {
+ const resources =
+ radioValue === "SELECT" ? databaseResources : undefined;
+
+ const resourceExpressions = (
+ resources?.map(getResourceExpressions) ?? [[""]]
+ ).map((parts) => parts.filter((e) => e).join(" && "));
+
+ let resourceCondition = "";
+ const nonEmpty = resourceExpressions.filter((e) => e);
+ if (nonEmpty.length === 1) {
+ resourceCondition = nonEmpty[0];
+ } else if (nonEmpty.length > 1) {
+ resourceCondition = nonEmpty.map((e) => `(${e})`).join(" || ");
+ }
+
+ const parts = [resourceCondition, ...extraExpressions].filter((e) => e);
+ exemptions.push(
+ create(MaskingExemptionPolicy_ExemptionSchema, {
+ members: memberList,
+ condition: create(ExprSchema, {
+ description,
+ expression: parts.length > 0 ? parts.join(" && ") : "",
+ }),
+ })
+ );
+ }
+
+ const policy = await policyStore.getOrFetchPolicyByParentAndType({
+ parentPath: projectName,
+ policyType: PolicyType.MASKING_EXEMPTION,
+ });
+ const existed =
+ policy?.policy?.case === "maskingExemptionPolicy"
+ ? policy.policy.value.exemptions
+ : [];
+
+ await policyStore.upsertPolicy({
+ parentPath: projectName,
+ policy: {
+ name: policy?.name,
+ type: PolicyType.MASKING_EXEMPTION,
+ resourceType: PolicyResourceType.PROJECT,
+ policy: {
+ case: "maskingExemptionPolicy",
+ value: create(MaskingExemptionPolicySchema, {
+ exemptions: [...existed, ...exemptions],
+ }),
+ },
+ },
+ });
+
+ pushNotification({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t("common.created"),
+ });
+ onDismissInternal();
+ } catch (error) {
+ pushNotification({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: `${error}`,
+ });
+ } finally {
+ setProcessing(false);
+ }
+ }, [
+ processing,
+ expirationTimestamp,
+ radioValue,
+ expr,
+ databaseResources,
+ memberList,
+ description,
+ projectName,
+ policyStore,
+ t,
+ onDismissInternal,
+ ]);
+
+ return (
+ <>
+ <Dialog
+ open={open}
+ onOpenChange={(nextOpen) => {
+ if (!nextOpen) {
+ onDismissInternal();
+ }
+ }}
+ >
+ <DialogContent className="p-6">
+ <DialogTitle>{t("settings.sensitive-data.grant-access")}</DialogTitle>
+ <div className="mt-4 flex flex-col gap-y-8">
+ <FeatureAttention
+ feature={PlanFeature.FEATURE_DATA_MASKING}
+ instance={instance}
+ />
+
+ <div className="w-full">
+ <div className="flex items-center gap-x-1 mb-2">
+ <span className="text-main">{t("common.resources")}</span>
+ <span className="text-error">*</span>
+ </div>
+
+ <div className="w-full mb-2">
+ <div className="flex flex-col sm:flex-row justify-start sm:items-center gap-2 sm:gap-4">
+ <Tooltip content={t("issue.role-grant.all-databases-tip")}>
+ <label className="flex items-center gap-x-2 cursor-pointer">
+ <input
+ type="radio"
+ name="resource-mode"
+ checked={radioValue === "ALL"}
+ onChange={() => onRadioChange("ALL")}
+ disabled={modeChangeProcessing}
+ className="accent-accent"
+ />
+ <span>{t("issue.role-grant.all-databases")}</span>
+ </label>
+ </Tooltip>
+
+ <label className="flex items-center gap-x-2 cursor-pointer">
+ <input
+ type="radio"
+ name="resource-mode"
+ checked={radioValue === "EXPRESSION"}
+ onChange={() => onRadioChange("EXPRESSION")}
+ disabled={modeChangeProcessing}
+ className="accent-accent"
+ />
+ <div className="flex items-center gap-x-1">
+ <FeatureBadge
+ feature={PlanFeature.FEATURE_DATA_MASKING}
+ instance={instance}
+ />
+ <span>{t("issue.role-grant.use-cel")}</span>
+ </div>
+ </label>
+
+ <label
+ className={`flex items-center gap-x-2 ${
+ selectModeDisabled
+ ? "cursor-not-allowed"
+ : "cursor-pointer"
+ }`}
+ >
+ <input
+ type="radio"
+ name="resource-mode"
+ checked={radioValue === "SELECT"}
+ onChange={() => onRadioChange("SELECT")}
+ disabled={selectModeDisabled || modeChangeProcessing}
+ className="accent-accent"
+ />
+ <Tooltip
+ content={
+ selectModeDisabled
+ ? t("issue.role-grant.column-scope-select-disabled")
+ : ""
+ }
+ >
+ <div
+ className={`flex items-center gap-x-1 ${
+ selectModeDisabled ? "cursor-not-allowed" : ""
+ }`}
+ >
+ <FeatureBadge
+ feature={PlanFeature.FEATURE_DATA_MASKING}
+ instance={instance}
+ />
+ <span>{t("issue.role-grant.manually-select")}</span>
+ </div>
+ </Tooltip>
+ </label>
+ </div>
+ </div>
+
+ {radioValue === "SELECT" && (
+ <DatabaseResourceSelector
+ projectName={projectName}
+ value={databaseResources}
+ onChange={setDatabaseResources}
+ />
+ )}
+ {radioValue === "EXPRESSION" && (
+ <ExprEditor
+ expr={expr}
+ factorList={factorList}
+ optionConfigMap={factorOptionConfigMap}
+ factorOperatorOverrideMap={factorOperatorOverrideMap}
+ onUpdate={setExpr}
+ />
+ )}
+ </div>
+
+ <div className="w-full">
+ <p className="mb-2 text-main">{t("common.reason")}</p>
+ <Input
+ value={description}
+ onChange={(event) => setDescription(event.target.value)}
+ placeholder={t("common.description")}
+ />
+ </div>
+
+ <div className="w-full">
+ <p className="mb-2 text-main">{t("common.expiration")}</p>
+ <ExpirationPicker
+ value={expirationTimestamp}
+ onChange={setExpirationTimestamp}
+ minDate={minDatetime}
+ />
+ {!expirationTimestamp && (
+ <span className="textinfolabel">
+ {t("settings.sensitive-data.never-expires")}
+ </span>
+ )}
+ </div>
+
+ <div className="w-full flex flex-col gap-y-2">
+ <div className="flex text-main items-center gap-x-1">
+ {t("settings.members.select-account", { count: 2 })}
+ <span className="text-error">*</span>
+ <Tooltip content={t("settings.members.select-account-hint")}>
+ <CircleHelp className="size-4 textinfolabel" />
+ </Tooltip>
+ </div>
+ <AccountMultiSelect value={memberList} onChange={setMemberList} />
+ </div>
+ </div>
+
+ <div className="mt-6 flex justify-end gap-x-2">
+ <Button variant="outline" onClick={onDismissInternal}>
+ {t("common.cancel")}
+ </Button>
+ <Button disabled={submitDisabled || processing} onClick={onSubmit}>
+ {t("common.confirm")}
+ </Button>
+ </div>
+ </DialogContent>
+ </Dialog>
+
+ <Dialog
+ open={showFeatureModal}
+ onOpenChange={(isOpen) => {
+ if (!isOpen) setShowFeatureModal(false);
+ }}
+ >
+ <DialogContent className="p-6">
+ <DialogTitle>{t("common.warning")}</DialogTitle>
+ <FeatureAttention
+ feature={PlanFeature.FEATURE_DATA_MASKING}
+ instance={instance}
+ />
+ <div className="flex justify-end gap-x-2 mt-4">
+ <Button
+ variant="outline"
+ onClick={() => setShowFeatureModal(false)}
+ >
+ {t("common.cancel")}
+ </Button>
+ </div>
+ </DialogContent>
+ </Dialog>
+ </>
+ );
+}
diff --git a/frontend/src/react/pages/project/database-detail/catalog/SensitiveColumnTable.tsx b/frontend/src/react/pages/project/database-detail/catalog/SensitiveColumnTable.tsx
new file mode 100644
index 0000000000..84d70ab590
--- /dev/null
+++ b/frontend/src/react/pages/project/database-detail/catalog/SensitiveColumnTable.tsx
@@ -0,0 +1,306 @@
+import { Trash2 } from "lucide-react";
+import { useEffect, useMemo, useRef } from "react";
+import { useTranslation } from "react-i18next";
+import type { MaskData } from "@/components/SensitiveData/types";
+import { Button } from "@/react/components/ui/button";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/react/components/ui/select";
+import {
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from "@/react/components/ui/table";
+import { router } from "@/router";
+import type { Database } from "@/types/proto-es/v1/database_service_pb";
+import { autoDatabaseRoute } from "@/utils";
+
+const EMPTY_SELECT_VALUE = "__EMPTY__";
+
+type SelectOption = {
+ label: string;
+ value: string;
+};
+
+function itemKey(item: MaskData) {
+ const parts = [];
+ if (item.schema) {
+ parts.push(item.schema);
+ }
+ parts.push(item.table, item.column);
+ return parts.join("::");
+}
+
+function EditableSelect({
+ value,
+ options,
+ disabled,
+ placeholder,
+ onValueChange,
+}: {
+ value: string;
+ options: SelectOption[];
+ disabled: boolean;
+ placeholder: string;
+ onValueChange: (value: string) => void;
+}) {
+ const normalizedValue = value || EMPTY_SELECT_VALUE;
+ const selectedLabel =
+ options.find((option) => option.value === value)?.label || placeholder;
+
+ return (
+ <Select
+ disabled={disabled}
+ value={normalizedValue}
+ onValueChange={(nextValue) =>
+ onValueChange(
+ !nextValue || nextValue === EMPTY_SELECT_VALUE ? "" : nextValue
+ )
+ }
+ >
+ <SelectTrigger className="w-full">
+ <SelectValue>{selectedLabel}</SelectValue>
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value={EMPTY_SELECT_VALUE}>{placeholder}</SelectItem>
+ {options.map((option) => (
+ <SelectItem key={option.value} value={option.value}>
+ {option.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ );
+}
+
+export function SensitiveColumnTable({
+ database,
+ columnList,
+ checkedColumnList,
+ showSelection,
+ canEdit,
+ showOperation,
+ semanticTypeOptions,
+ classificationOptions,
+ onCheckedColumnListChange,
+ onSemanticTypeChange,
+ onClassificationChange,
+ onDelete,
+}: {
+ database: Database;
+ columnList: MaskData[];
+ checkedColumnList: MaskData[];
+ showSelection: boolean;
+ canEdit: boolean;
+ showOperation: boolean;
+ semanticTypeOptions: SelectOption[];
+ classificationOptions: SelectOption[];
+ onCheckedColumnListChange: (columnList: MaskData[]) => void;
+ onSemanticTypeChange: (
+ item: MaskData,
+ semanticTypeId: string
+ ) => void | Promise<void>;
+ onClassificationChange: (
+ item: MaskData,
+ classificationId: string
+ ) => void | Promise<void>;
+ onDelete: (item: MaskData) => void;
+}) {
+ const { t } = useTranslation();
+ const headerCheckboxRef = useRef<HTMLInputElement>(null);
+ const checkedKeySet = useMemo(
+ () => new Set(checkedColumnList.map(itemKey)),
+ [checkedColumnList]
+ );
+ const showSelectionColumn = showSelection && columnList.length > 0;
+ const visibleSelectedCount = useMemo(
+ () => columnList.filter((item) => checkedKeySet.has(itemKey(item))).length,
+ [columnList, checkedKeySet]
+ );
+ const allSelected =
+ columnList.length > 0 && visibleSelectedCount === columnList.length;
+ const someSelected =
+ visibleSelectedCount > 0 && visibleSelectedCount < columnList.length;
+
+ useEffect(() => {
+ if (headerCheckboxRef.current) {
+ headerCheckboxRef.current.indeterminate = someSelected;
+ if (!someSelected) {
+ headerCheckboxRef.current.indeterminate = false;
+ }
+ }
+ }, [someSelected]);
+
+ const toggleSelection = (item: MaskData) => {
+ const key = itemKey(item);
+ if (checkedKeySet.has(key)) {
+ onCheckedColumnListChange(
+ checkedColumnList.filter(
+ (selectedItem) => itemKey(selectedItem) !== key
+ )
+ );
+ return;
+ }
+ onCheckedColumnListChange([...checkedColumnList, item]);
+ };
+
+ const toggleSelectAll = () => {
+ if (allSelected) {
+ const visibleKeySet = new Set(columnList.map(itemKey));
+ onCheckedColumnListChange(
+ checkedColumnList.filter((item) => !visibleKeySet.has(itemKey(item)))
+ );
+ return;
+ }
+ const next = [...checkedColumnList];
+ for (const item of columnList) {
+ if (!checkedKeySet.has(itemKey(item))) {
+ next.push(item);
+ }
+ }
+ onCheckedColumnListChange(next);
+ };
+
+ return (
+ <div className="overflow-x-auto rounded border border-block-border">
+ <Table className="min-w-full">
+ <TableHeader className="bg-control-bg">
+ <TableRow className="hover:bg-control-bg">
+ {showSelectionColumn && (
+ <TableHead className="w-12">
+ <input
+ ref={headerCheckboxRef}
+ type="checkbox"
+ checked={allSelected}
+ onChange={toggleSelectAll}
+ onClick={(event) => event.stopPropagation()}
+ className="rounded-xs border-control-border"
+ />
+ </TableHead>
+ )}
+ <TableHead>{t("common.table")}</TableHead>
+ <TableHead>{t("database.column")}</TableHead>
+ <TableHead>
+ {t("settings.sensitive-data.semantic-types.table.semantic-type")}
+ </TableHead>
+ <TableHead>{t("database.classification.self")}</TableHead>
+ {showOperation && (
+ <TableHead className="w-16">{t("common.operation")}</TableHead>
+ )}
+ </TableRow>
+ </TableHeader>
+ <TableBody className="bg-background">
+ {columnList.length === 0 ? (
+ <TableRow>
+ <TableCell
+ className="py-6 text-center text-control-light"
+ colSpan={
+ (showSelectionColumn ? 1 : 0) + 4 + (showOperation ? 1 : 0)
+ }
+ >
+ {t("common.no-data")}
+ </TableCell>
+ </TableRow>
+ ) : (
+ columnList.map((item) => {
+ const key = itemKey(item);
+ const isChecked = checkedKeySet.has(key);
+ const semanticTypeDisabled =
+ !canEdit || !!item.disableSemanticType;
+ const classificationDisabled =
+ !canEdit || !!item.disableClassification;
+
+ return (
+ <TableRow
+ key={key}
+ data-state={isChecked ? "selected" : undefined}
+ >
+ {showSelectionColumn && (
+ <TableCell className="w-12">
+ <input
+ type="checkbox"
+ checked={isChecked}
+ onChange={() => toggleSelection(item)}
+ onClick={(event) => event.stopPropagation()}
+ className="rounded-xs border-control-border"
+ />
+ </TableCell>
+ )}
+ <TableCell className="text-main">
+ <a
+ className="normal-link"
+ href={
+ router.resolve({
+ ...autoDatabaseRoute(database),
+ query: {
+ schema: item.schema,
+ table: item.table,
+ },
+ hash: "overview",
+ }).fullPath
+ }
+ >
+ {item.schema
+ ? `${item.schema}.${item.table}`
+ : item.table}
+ </a>
+ </TableCell>
+ <TableCell className="text-main">
+ {item.column || t("common.empty")}
+ </TableCell>
+ <TableCell>
+ <EditableSelect
+ value={item.semanticTypeId}
+ options={semanticTypeOptions}
+ disabled={semanticTypeDisabled}
+ placeholder={t("common.empty")}
+ onValueChange={(semanticTypeId) =>
+ void onSemanticTypeChange(item, semanticTypeId)
+ }
+ />
+ </TableCell>
+ <TableCell>
+ <EditableSelect
+ value={item.classificationId}
+ options={classificationOptions}
+ disabled={classificationDisabled}
+ placeholder={t("common.empty")}
+ onValueChange={(classificationId) =>
+ void onClassificationChange(item, classificationId)
+ }
+ />
+ </TableCell>
+ {showOperation && (
+ <TableCell className="w-16">
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ onClick={() => onDelete(item)}
+ title={t(
+ "settings.sensitive-data.remove-sensitive-column-tips"
+ )}
+ aria-label={t(
+ "settings.sensitive-data.remove-sensitive-column-tips"
+ )}
+ >
+ <Trash2 className="h-4 w-4" />
+ </Button>
+ </TableCell>
+ )}
+ </TableRow>
+ );
+ })
+ )}
+ </TableBody>
+ </Table>
+ </div>
+ );
+}
diff --git a/frontend/src/react/pages/project/database-detail/panels/DatabaseCatalogPanel.test.tsx b/frontend/src/react/pages/project/database-detail/panels/DatabaseCatalogPanel.test.tsx
new file mode 100644
index 0000000000..9ba5212b0c
--- /dev/null
+++ b/frontend/src/react/pages/project/database-detail/panels/DatabaseCatalogPanel.test.tsx
@@ -0,0 +1,917 @@
+import type {
+ ButtonHTMLAttributes,
+ InputHTMLAttributes,
+ ReactNode,
+} from "react";
+import { act, createElement } from "react";
+import { createRoot } from "react-dom/client";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+import type { DatabaseCatalog } from "@/types/proto-es/v1/database_catalog_service_pb";
+import { ObjectSchema_Type } from "@/types/proto-es/v1/database_catalog_service_pb";
+import type { Database } from "@/types/proto-es/v1/database_service_pb";
+import { Setting_SettingName } from "@/types/proto-es/v1/setting_service_pb";
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+const makeColumn = (
+ overrides: Partial<{
+ name: string;
+ semanticType: string;
+ classification: string;
+ }> = {}
+) => ({
+ name: overrides.name ?? "email",
+ semanticType: overrides.semanticType ?? "EMAIL",
+ classification: overrides.classification ?? "PII",
+});
+
+const makeObjectSchema = () => ({
+ type: ObjectSchema_Type.OBJECT,
+ semanticType: "",
+ kind: {
+ case: "structKind" as const,
+ value: {
+ properties: {
+ contact: {
+ type: ObjectSchema_Type.OBJECT,
+ semanticType: "",
+ kind: {
+ case: "structKind" as const,
+ value: {
+ properties: {
+ email: {
+ type: ObjectSchema_Type.STRING,
+ semanticType: "EMAIL",
+ },
+ phone: {
+ type: ObjectSchema_Type.STRING,
+ semanticType: "PHONE",
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+});
+
+const makeDatabaseCatalog = (): DatabaseCatalog =>
+ ({
+ schemas: [
+ {
+ name: "public",
+ tables: [
+ {
+ name: "book",
+ kind: {
+ case: "columns",
+ value: {
+ columns: [makeColumn()],
+ },
+ },
+ classification: "",
+ },
+ {
+ name: "profile",
+ kind: {
+ case: "objectSchema",
+ value: makeObjectSchema(),
+ },
+ classification: "",
+ },
+ ],
+ },
+ ],
+ }) as DatabaseCatalog;
+
+const makeSimpleCatalog = (): DatabaseCatalog =>
+ ({
+ schemas: [
+ {
+ name: "public",
+ tables: [
+ {
+ name: "book",
+ kind: {
+ case: "columns",
+ value: {
+ columns: [makeColumn()],
+ },
+ },
+ classification: "",
+ },
+ ],
+ },
+ ],
+ }) as DatabaseCatalog;
+
+const makeDatabase = (): Database =>
+ ({
+ name: "instances/inst1/databases/db1",
+ project: "projects/proj1",
+ }) as Database;
+
+const click = (element: HTMLElement) => {
+ act(() => {
+ element.dispatchEvent(
+ new MouseEvent("click", { bubbles: true, cancelable: true })
+ );
+ });
+};
+
+const changeSelect = async (select: HTMLSelectElement, value: string) => {
+ act(() => {
+ const descriptor = Object.getOwnPropertyDescriptor(
+ HTMLSelectElement.prototype,
+ "value"
+ );
+ descriptor?.set?.call(select, value);
+ select.dispatchEvent(new Event("change", { bubbles: true }));
+ });
+
+ await flush();
+};
+
+const flush = async () => {
+ await act(async () => {
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+};
+
+const renderIntoContainer = (element: ReturnType<typeof createElement>) => {
+ const container = document.createElement("div");
+ const root = createRoot(container);
+ return {
+ container,
+ render: (nextElement = element) => {
+ act(() => {
+ root.render(nextElement);
+ });
+ },
+ unmount: () =>
+ act(() => {
+ root.unmount();
+ }),
+ };
+};
+
+const mocks = vi.hoisted(() => {
+ const localStorage = {
+ clear: vi.fn(),
+ getItem: vi.fn(() => null),
+ removeItem: vi.fn(),
+ setItem: vi.fn(),
+ };
+
+ vi.stubGlobal("localStorage", localStorage);
+
+ const hasProjectPermissionV2 = vi.fn(
+ (_project?: unknown, _permission?: string) => true
+ );
+
+ return {
+ localStorage,
+ featureToRef: vi.fn(() => ({ value: true })),
+ useVueState: vi.fn((getter: () => unknown) => getter()),
+ useDatabaseCatalog: vi.fn(() => ({
+ value: makeDatabaseCatalog(),
+ })),
+ usePolicyV1Store: vi.fn(() => ({
+ getOrFetchPolicyByParentAndType: vi.fn(),
+ upsertPolicy: vi.fn(),
+ })),
+ useDatabaseCatalogV1Store: vi.fn(() => ({
+ updateDatabaseCatalog: vi.fn(),
+ })),
+ useSettingV1Store: vi.fn(() => ({
+ getOrFetchSettingByName: vi.fn(),
+ getProjectClassification: vi.fn(() => ({
+ id: "classification-config",
+ classification: {
+ PII: {
+ id: "PII",
+ title: "PII",
+ },
+ CONFIDENTIAL: {
+ id: "CONFIDENTIAL",
+ title: "Confidential",
+ },
+ },
+ })),
+ getSettingByName: vi.fn(() => ({
+ value: {
+ value: {
+ case: "semanticType",
+ value: {
+ types: [
+ {
+ id: "EMAIL",
+ title: "Email",
+ },
+ {
+ id: "PHONE",
+ title: "Phone",
+ },
+ ],
+ },
+ },
+ },
+ })),
+ })),
+ pushNotification: vi.fn(),
+ getDatabaseProject: vi.fn((database: { project: string }) => ({
+ name: database.project,
+ dataClassificationConfigId: "classification-config",
+ })),
+ getInstanceResource: vi.fn(() => ({
+ name: "instances/inst1",
+ engine: 1,
+ })),
+ instanceV1MaskingForNoSQL: vi.fn(() => false),
+ hasProjectPermissionV2,
+ autoDatabaseRoute: vi.fn(() => ({ name: "database" })),
+ routerResolve: vi.fn(() => ({ fullPath: "/database/route" })),
+ PermissionGuard: vi.fn(
+ ({
+ project,
+ permissions,
+ children,
+ }: {
+ project?: { name: string };
+ permissions: string[];
+ children: (props: { disabled: boolean }) => ReactNode;
+ }) => {
+ const disabled =
+ !project ||
+ !permissions.every((permission) =>
+ hasProjectPermissionV2(project, permission)
+ );
+ return children({ disabled });
+ }
+ ),
+ FeatureAttention: vi.fn(() => <div data-testid="feature-attention" />),
+ FeatureBadge: vi.fn(() => <div data-testid="feature-badge" />),
+ Button: (props: ButtonHTMLAttributes<HTMLButtonElement>) => (
+ <button {...props} />
+ ),
+ Input: (props: InputHTMLAttributes<HTMLInputElement>) => (
+ <input {...props} />
+ ),
+ Dialog: ({ open, children }: { open: boolean; children: ReactNode }) =>
+ open ? <div data-testid="dialog-root">{children}</div> : null,
+ DialogContent: ({ children }: { children: ReactNode }) => (
+ <div>{children}</div>
+ ),
+ DialogTitle: ({ children }: { children: ReactNode }) => <h1>{children}</h1>,
+ AlertDialog: ({
+ open,
+ children,
+ }: {
+ open: boolean;
+ children: ReactNode;
+ }) => (open ? <div data-testid="alert-dialog-root">{children}</div> : null),
+ AlertDialogContent: ({ children }: { children: ReactNode }) => (
+ <div>{children}</div>
+ ),
+ AlertDialogClose: ({ children }: { children: ReactNode }) => (
+ <>{children}</>
+ ),
+ AlertDialogDescription: ({ children }: { children: ReactNode }) => (
+ <p>{children}</p>
+ ),
+ AlertDialogFooter: ({ children }: { children: ReactNode }) => (
+ <div>{children}</div>
+ ),
+ AlertDialogTitle: ({ children }: { children: ReactNode }) => (
+ <h1>{children}</h1>
+ ),
+ Select: ({
+ value,
+ disabled,
+ onValueChange,
+ children,
+ }: {
+ value?: string;
+ disabled?: boolean;
+ onValueChange?: (value: string) => void;
+ children: ReactNode;
+ }) => (
+ <select
+ value={value}
+ disabled={disabled}
+ onChange={(event) => onValueChange?.(event.target.value)}
+ >
+ {children}
+ </select>
+ ),
+ SelectTrigger: ({ children }: { children: ReactNode }) => <>{children}</>,
+ SelectValue: ({ children }: { children: ReactNode }) => (
+ <option value="">{children}</option>
+ ),
+ SelectContent: ({ children }: { children: ReactNode }) => <>{children}</>,
+ SelectItem: ({
+ value,
+ children,
+ }: {
+ value: string;
+ children: ReactNode;
+ }) => <option value={value}>{children}</option>,
+ Tooltip: ({
+ content,
+ children,
+ }: {
+ content: ReactNode;
+ children: ReactNode;
+ }) => (
+ <span data-testid="tooltip" data-content={String(content)}>
+ {children}
+ </span>
+ ),
+ DatabaseResourceSelector: vi.fn(() => (
+ <div data-testid="resource-selector" />
+ )),
+ ExprEditor: vi.fn(() => <div data-testid="expr-editor" />),
+ AccountMultiSelect: vi.fn(() => <div data-testid="account-multi-select" />),
+ ExpirationPicker: vi.fn(() => <div data-testid="expiration-picker" />),
+ GrantAccessDialog: vi.fn(
+ ({
+ open,
+ columnList,
+ }: {
+ open: boolean;
+ columnList: Array<{ maskData: { column: string } }>;
+ }) => (
+ <div
+ data-testid="grant-access-dialog"
+ data-open={open ? "true" : "false"}
+ data-column-count={columnList.length}
+ data-columns={JSON.stringify(
+ columnList.map(({ maskData }) => maskData.column)
+ )}
+ />
+ )
+ ),
+ useTranslation: vi.fn(() => ({
+ t: (key: string) => key,
+ })),
+ };
+});
+
+let DatabaseCatalogPanel: typeof import("./DatabaseCatalogPanel").DatabaseCatalogPanel;
+
+vi.stubGlobal("localStorage", mocks.localStorage);
+
+vi.mock("react-i18next", () => ({
+ useTranslation: mocks.useTranslation,
+}));
+
+vi.mock("@/react/hooks/useVueState", () => ({
+ useVueState: mocks.useVueState,
+}));
+
+vi.mock("@/store", () => ({
+ featureToRef: mocks.featureToRef,
+ pushNotification: mocks.pushNotification,
+ useDatabaseCatalog: mocks.useDatabaseCatalog,
+ useDatabaseCatalogV1Store: mocks.useDatabaseCatalogV1Store,
+ usePolicyV1Store: mocks.usePolicyV1Store,
+ useSettingV1Store: mocks.useSettingV1Store,
+}));
+
+vi.mock("@/utils", () => ({
+ autoDatabaseRoute: mocks.autoDatabaseRoute,
+ getDatabaseProject: mocks.getDatabaseProject,
+ getInstanceResource: mocks.getInstanceResource,
+ hasProjectPermissionV2: mocks.hasProjectPermissionV2,
+ instanceV1MaskingForNoSQL: mocks.instanceV1MaskingForNoSQL,
+}));
+
+vi.mock("@/router", () => ({
+ router: {
+ resolve: mocks.routerResolve,
+ },
+}));
+
+vi.mock("@/react/components/FeatureAttention", () => ({
+ FeatureAttention: mocks.FeatureAttention,
+}));
+
+vi.mock("@/react/components/FeatureBadge", () => ({
+ FeatureBadge: mocks.FeatureBadge,
+}));
+
+vi.mock("@/react/components/PermissionGuard", () => ({
+ PermissionGuard: mocks.PermissionGuard,
+}));
+
+vi.mock("@/react/components/ui/alert-dialog", () => ({
+ AlertDialog: mocks.AlertDialog,
+ AlertDialogClose: mocks.AlertDialogClose,
+ AlertDialogContent: mocks.AlertDialogContent,
+ AlertDialogDescription: mocks.AlertDialogDescription,
+ AlertDialogFooter: mocks.AlertDialogFooter,
+ AlertDialogTitle: mocks.AlertDialogTitle,
+}));
+
+vi.mock("@/react/components/ui/button", () => ({
+ Button: mocks.Button,
+}));
+
+vi.mock("@/react/components/ui/dialog", () => ({
+ Dialog: mocks.Dialog,
+ DialogContent: mocks.DialogContent,
+ DialogTitle: mocks.DialogTitle,
+}));
+
+vi.mock("@/react/components/ui/input", () => ({
+ Input: mocks.Input,
+}));
+
+vi.mock("@/react/components/ui/select", () => ({
+ Select: mocks.Select,
+ SelectContent: mocks.SelectContent,
+ SelectItem: mocks.SelectItem,
+ SelectTrigger: mocks.SelectTrigger,
+ SelectValue: mocks.SelectValue,
+}));
+
+vi.mock("@/react/components/ui/tooltip", () => ({
+ Tooltip: mocks.Tooltip,
+}));
+
+vi.mock("../catalog/GrantAccessDialog", () => ({
+ GrantAccessDialog: mocks.GrantAccessDialog,
+}));
+
+const getButton = (container: HTMLElement, label: string) =>
+ Array.from(container.querySelectorAll("button")).find(
+ (button) => button.textContent === label
+ );
+
+const getCheckboxes = (container: HTMLElement) =>
+ Array.from(
+ container.querySelectorAll('input[type="checkbox"]')
+ ) as HTMLInputElement[];
+
+beforeEach(async () => {
+ vi.stubGlobal("localStorage", mocks.localStorage);
+ mocks.useTranslation.mockReset();
+ mocks.useTranslation.mockReturnValue({
+ t: (key: string) => key,
+ });
+ mocks.useVueState.mockReset();
+ mocks.useVueState.mockImplementation((getter: () => unknown) => getter());
+ mocks.useDatabaseCatalog.mockReset();
+ mocks.useDatabaseCatalog.mockReturnValue({
+ value: makeDatabaseCatalog(),
+ });
+ mocks.usePolicyV1Store.mockReset();
+ mocks.usePolicyV1Store.mockReturnValue({
+ getOrFetchPolicyByParentAndType: vi.fn(),
+ upsertPolicy: vi.fn(),
+ });
+ mocks.useDatabaseCatalogV1Store.mockReset();
+ mocks.useDatabaseCatalogV1Store.mockReturnValue({
+ updateDatabaseCatalog: vi.fn(),
+ });
+ mocks.useSettingV1Store.mockReset();
+ mocks.useSettingV1Store.mockReturnValue({
+ getOrFetchSettingByName: vi.fn(),
+ getProjectClassification: vi.fn(() => ({
+ id: "classification-config",
+ classification: {
+ PII: {
+ id: "PII",
+ title: "PII",
+ },
+ CONFIDENTIAL: {
+ id: "CONFIDENTIAL",
+ title: "Confidential",
+ },
+ },
+ })),
+ getSettingByName: vi.fn(() => ({
+ value: {
+ value: {
+ case: "semanticType",
+ value: {
+ types: [
+ {
+ id: "EMAIL",
+ title: "Email",
+ },
+ {
+ id: "PHONE",
+ title: "Phone",
+ },
+ ],
+ },
+ },
+ },
+ })),
+ });
+ mocks.pushNotification.mockReset();
+ mocks.getDatabaseProject.mockReset();
+ mocks.getDatabaseProject.mockImplementation(
+ (database: { project: string }) => ({
+ name: database.project,
+ dataClassificationConfigId: "classification-config",
+ })
+ );
+ mocks.getInstanceResource.mockReset();
+ mocks.getInstanceResource.mockReturnValue({
+ name: "instances/inst1",
+ engine: 1,
+ });
+ mocks.instanceV1MaskingForNoSQL.mockReset();
+ mocks.instanceV1MaskingForNoSQL.mockReturnValue(false);
+ mocks.featureToRef.mockReset();
+ mocks.featureToRef.mockReturnValue({ value: true });
+ mocks.hasProjectPermissionV2.mockReset();
+ mocks.hasProjectPermissionV2.mockReturnValue(true);
+ mocks.PermissionGuard.mockClear();
+ mocks.FeatureAttention.mockClear();
+ mocks.FeatureBadge.mockClear();
+ mocks.GrantAccessDialog.mockClear();
+ mocks.DatabaseResourceSelector.mockClear();
+ mocks.ExprEditor.mockClear();
+ mocks.AccountMultiSelect.mockClear();
+ mocks.ExpirationPicker.mockClear();
+ mocks.autoDatabaseRoute.mockClear();
+ mocks.routerResolve.mockClear();
+ vi.resetModules();
+ ({ DatabaseCatalogPanel } = await import("./DatabaseCatalogPanel"));
+});
+
+describe("DatabaseCatalogPanel", () => {
+ test("renders flattened relational and object-schema rows", async () => {
+ const { container, render, unmount } = renderIntoContainer(
+ createElement(DatabaseCatalogPanel, {
+ database: makeDatabase(),
+ })
+ );
+
+ render();
+ await flush();
+
+ expect(container.textContent).toContain("public.book");
+ expect(container.textContent).toContain("email");
+ expect(container.textContent).toContain("public.profile");
+ expect(container.textContent).toContain("contact.email");
+
+ unmount();
+ });
+
+ test("enables grant access after selecting a row", async () => {
+ const { container, render, unmount } = renderIntoContainer(
+ createElement(DatabaseCatalogPanel, {
+ database: makeDatabase(),
+ })
+ );
+
+ render();
+ await flush();
+
+ const grantAccessButton = getButton(
+ container,
+ "settings.sensitive-data.grant-access"
+ );
+ expect(grantAccessButton?.hasAttribute("disabled")).toBe(true);
+
+ const checkboxes = getCheckboxes(container);
+ expect(checkboxes).toHaveLength(4);
+ click(checkboxes[1]);
+ await flush();
+
+ const enabledGrantAccessButton = getButton(
+ container,
+ "settings.sensitive-data.grant-access"
+ );
+ expect(enabledGrantAccessButton?.hasAttribute("disabled")).toBe(false);
+
+ unmount();
+ });
+
+ test("opens the feature dialog instead of grant access when masking feature is missing", async () => {
+ mocks.featureToRef.mockReturnValue({ value: false });
+
+ const { container, render, unmount } = renderIntoContainer(
+ createElement(DatabaseCatalogPanel, {
+ database: makeDatabase(),
+ })
+ );
+
+ render();
+ await flush();
+
+ const checkboxes = getCheckboxes(container);
+ expect(checkboxes).toHaveLength(4);
+ click(checkboxes[1]);
+ await flush();
+
+ click(
+ getButton(
+ container,
+ "settings.sensitive-data.grant-access"
+ ) as HTMLElement
+ );
+ await flush();
+
+ expect(
+ container.querySelector('[data-testid="dialog-root"]')
+ ).not.toBeNull();
+ expect(container.textContent).toContain("common.warning");
+ expect(mocks.GrantAccessDialog).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ open: false,
+ }),
+ undefined
+ );
+ expect(
+ container
+ .querySelector('[data-testid="grant-access-dialog"]')
+ ?.getAttribute("data-open")
+ ).toBe("false");
+
+ unmount();
+ });
+
+ test("passes permission inputs to the grant-access guard", async () => {
+ const { render, unmount } = renderIntoContainer(
+ createElement(DatabaseCatalogPanel, {
+ database: makeDatabase(),
+ })
+ );
+
+ render();
+ await flush();
+
+ expect(mocks.PermissionGuard).toHaveBeenCalledWith(
+ expect.objectContaining({
+ permissions: [
+ "bb.policies.createMaskingExemptionPolicy",
+ "bb.policies.updateMaskingExemptionPolicy",
+ "bb.databaseCatalogs.get",
+ ],
+ project: expect.objectContaining({
+ name: "projects/proj1",
+ }),
+ }),
+ undefined
+ );
+
+ unmount();
+ });
+
+ test("clears a selected row from checked selection when deleted", async () => {
+ const updateDatabaseCatalog = vi.fn().mockResolvedValue(undefined);
+ mocks.useDatabaseCatalogV1Store.mockReturnValue({
+ updateDatabaseCatalog,
+ });
+
+ const { container, render, unmount } = renderIntoContainer(
+ createElement(DatabaseCatalogPanel, {
+ database: makeDatabase(),
+ })
+ );
+
+ render();
+ await flush();
+
+ const checkboxes = getCheckboxes(container);
+ expect(checkboxes).toHaveLength(4);
+ click(checkboxes[1]);
+ await flush();
+
+ expect(
+ getButton(
+ container,
+ "settings.sensitive-data.grant-access"
+ )?.hasAttribute("disabled")
+ ).toBe(false);
+
+ const deleteButton = container.querySelector(
+ 'button[aria-label="settings.sensitive-data.remove-sensitive-column-tips"]'
+ );
+ expect(deleteButton).not.toBeNull();
+ click(deleteButton as HTMLElement);
+ await flush();
+
+ const confirmButton = getButton(container, "common.delete");
+ expect(confirmButton).not.toBeNull();
+ click(confirmButton as HTMLElement);
+ await flush();
+
+ expect(updateDatabaseCatalog).toHaveBeenCalledTimes(1);
+ expect(
+ getButton(
+ container,
+ "settings.sensitive-data.grant-access"
+ )?.hasAttribute("disabled")
+ ).toBe(true);
+
+ unmount();
+ });
+
+ test("updates semantic type and classification independently", async () => {
+ const updateDatabaseCatalog = vi.fn().mockResolvedValue(undefined);
+ const getOrFetchSettingByName = vi.fn();
+ mocks.useDatabaseCatalogV1Store.mockReturnValue({
+ updateDatabaseCatalog,
+ });
+ mocks.useSettingV1Store.mockReturnValue({
+ getOrFetchSettingByName,
+ getProjectClassification: vi.fn(() => ({
+ id: "classification-config",
+ classification: {
+ PII: {
+ id: "PII",
+ title: "PII",
+ },
+ CONFIDENTIAL: {
+ id: "CONFIDENTIAL",
+ title: "Confidential",
+ },
+ },
+ })),
+ getSettingByName: vi.fn(() => ({
+ value: {
+ value: {
+ case: "semanticType",
+ value: {
+ types: [
+ {
+ id: "EMAIL",
+ title: "Email",
+ },
+ {
+ id: "PHONE",
+ title: "Phone",
+ },
+ ],
+ },
+ },
+ },
+ })),
+ });
+ const catalog = makeSimpleCatalog();
+ mocks.useDatabaseCatalog.mockReturnValue({
+ value: catalog,
+ });
+
+ const { container, render, unmount } = renderIntoContainer(
+ createElement(DatabaseCatalogPanel, {
+ database: makeDatabase(),
+ })
+ );
+
+ render();
+ await flush();
+
+ expect(getOrFetchSettingByName).toHaveBeenCalledWith(
+ Setting_SettingName.SEMANTIC_TYPES,
+ true
+ );
+ expect(getOrFetchSettingByName).toHaveBeenCalledWith(
+ Setting_SettingName.DATA_CLASSIFICATION,
+ true
+ );
+
+ const selects = Array.from(container.querySelectorAll("select"));
+ expect(selects).toHaveLength(2);
+
+ await changeSelect(selects[0] as HTMLSelectElement, "");
+ expect(updateDatabaseCatalog).toHaveBeenCalledTimes(1);
+ const table = catalog.schemas[0]?.tables[0];
+ expect(table?.kind.case).toBe("columns");
+ if (!table || table.kind.case !== "columns") {
+ throw new Error("expected a column-backed table catalog");
+ }
+ expect(table.kind.value.columns[0]?.semanticType).toBe("");
+ expect(table.kind.value.columns[0]?.classification).toBe("PII");
+
+ await changeSelect(selects[1] as HTMLSelectElement, "");
+ expect(updateDatabaseCatalog).toHaveBeenCalledTimes(2);
+ expect(table.kind.value.columns[0]?.classification).toBe("");
+
+ expect(mocks.pushNotification).toHaveBeenCalledWith(
+ expect.objectContaining({
+ style: "SUCCESS",
+ title: "common.updated",
+ })
+ );
+
+ unmount();
+ });
+
+ test("renders an empty state when catalog data is not loaded", async () => {
+ mocks.useDatabaseCatalog.mockReturnValue({
+ value: undefined as unknown as DatabaseCatalog,
+ });
+
+ const { container, render, unmount } = renderIntoContainer(
+ createElement(DatabaseCatalogPanel, {
+ database: makeDatabase(),
+ })
+ );
+
+ render();
+ await flush();
+
+ expect(container.textContent).toContain("common.no-data");
+ expect(container.querySelector('input[type="checkbox"]')).toBeNull();
+
+ unmount();
+ });
+
+ test("disables row selection in NoSQL mode and keeps object-schema rows", async () => {
+ mocks.instanceV1MaskingForNoSQL.mockReturnValue(true);
+
+ const { container, render, unmount } = renderIntoContainer(
+ createElement(DatabaseCatalogPanel, {
+ database: makeDatabase(),
+ })
+ );
+
+ render();
+ await flush();
+
+ expect(container.querySelector('input[type="checkbox"]')).toBeNull();
+ expect(container.textContent).toContain("public.profile");
+ expect(container.textContent).toContain("contact.email");
+
+ unmount();
+ });
+
+ test("guards column-scoped grant-access selections in the dialog", async () => {
+ const { container, render, unmount } = renderIntoContainer(
+ createElement(DatabaseCatalogPanel, {
+ database: makeDatabase(),
+ })
+ );
+
+ render();
+ await flush();
+
+ const checkboxes = getCheckboxes(container);
+ expect(checkboxes).toHaveLength(4);
+ click(checkboxes[0]);
+ await flush();
+
+ click(
+ getButton(
+ container,
+ "settings.sensitive-data.grant-access"
+ ) as HTMLElement
+ );
+ await flush();
+
+ const grantAccessDialog = container.querySelector(
+ '[data-testid="grant-access-dialog"]'
+ );
+ expect(grantAccessDialog?.getAttribute("data-open")).toBe("true");
+ expect(grantAccessDialog?.getAttribute("data-column-count")).toBe("3");
+ expect(grantAccessDialog?.getAttribute("data-columns")).toContain("email");
+ expect(grantAccessDialog?.getAttribute("data-columns")).toContain(
+ "contact.email"
+ );
+ expect(grantAccessDialog?.getAttribute("data-columns")).toContain(
+ "contact.phone"
+ );
+
+ unmount();
+ });
+
+ test("hides operation controls when catalog update permission is missing", async () => {
+ mocks.hasProjectPermissionV2.mockImplementation(
+ (_project?: unknown, permission?: string) =>
+ permission !== "bb.databaseCatalogs.update"
+ );
+
+ const { container, render, unmount } = renderIntoContainer(
+ createElement(DatabaseCatalogPanel, {
+ database: makeDatabase(),
+ })
+ );
+
+ render();
+ await flush();
+
+ const select = container.querySelector(
+ "select"
+ ) as HTMLSelectElement | null;
+ expect(select).not.toBeNull();
+ expect(select?.disabled).toBe(true);
+ expect(
+ container.querySelector(
+ 'button[aria-label="settings.sensitive-data.remove-sensitive-column-tips"]'
+ )
+ ).toBeNull();
+
+ unmount();
+ });
+});
diff --git a/frontend/src/react/pages/project/database-detail/panels/DatabaseCatalogPanel.tsx b/frontend/src/react/pages/project/database-detail/panels/DatabaseCatalogPanel.tsx
index dfd8a08ec8..92d896539b 100644
--- a/frontend/src/react/pages/project/database-detail/panels/DatabaseCatalogPanel.tsx
+++ b/frontend/src/react/pages/project/database-detail/panels/DatabaseCatalogPanel.tsx
@@ -1,47 +1,551 @@
-import { NConfigProvider } from "naive-ui";
-import { useEffect, useRef } from "react";
-import { createApp, h } from "vue";
-import { themeOverrides } from "@/../naive-ui.config";
-import DatabaseSensitiveDataPanel from "@/components/Database/DatabaseSensitiveDataPanel.vue";
-import OverlayStackManager from "@/components/misc/OverlayStackManager.vue";
-import i18n from "@/plugins/i18n";
-import NaiveUI from "@/plugins/naive-ui";
-import { router } from "@/router";
-import { pinia } from "@/store";
+import { create } from "@bufbuild/protobuf";
+import { ShieldCheck } from "lucide-react";
+import { useEffect, useMemo, useState } from "react";
+import { useTranslation } from "react-i18next";
+import type {
+ MaskData,
+ MaskDataTarget,
+} from "@/components/SensitiveData/types";
+import {
+ getMaskDataIdentifier,
+ isCurrentColumnException,
+} from "@/components/SensitiveData/utils";
+import { FeatureAttention } from "@/react/components/FeatureAttention";
+import { FeatureBadge } from "@/react/components/FeatureBadge";
+import { PermissionGuard } from "@/react/components/PermissionGuard";
+import {
+ AlertDialog,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogTitle,
+} from "@/react/components/ui/alert-dialog";
+import { Button } from "@/react/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogTitle,
+} from "@/react/components/ui/dialog";
+import { Input } from "@/react/components/ui/input";
+import { useVueState } from "@/react/hooks/useVueState";
+import {
+ featureToRef,
+ pushNotification,
+ useDatabaseCatalog,
+ useDatabaseCatalogV1Store,
+ usePolicyV1Store,
+ useSettingV1Store,
+} from "@/store";
+import type { Permission } from "@/types";
+import type {
+ ColumnCatalog,
+ DatabaseCatalog,
+ ObjectSchema,
+ TableCatalog,
+} from "@/types/proto-es/v1/database_catalog_service_pb";
+import { ObjectSchema_Type } from "@/types/proto-es/v1/database_catalog_service_pb";
import type { Database } from "@/types/proto-es/v1/database_service_pb";
+import {
+ MaskingExemptionPolicySchema,
+ PolicyType,
+} from "@/types/proto-es/v1/org_policy_service_pb";
+import {
+ type SemanticTypeSetting_SemanticType,
+ Setting_SettingName,
+} from "@/types/proto-es/v1/setting_service_pb";
+import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";
+import {
+ getDatabaseProject,
+ getInstanceResource,
+ hasProjectPermissionV2,
+ instanceV1MaskingForNoSQL,
+} from "@/utils";
+import { GrantAccessDialog } from "../catalog/GrantAccessDialog";
+import { SensitiveColumnTable } from "../catalog/SensitiveColumnTable";
-export function DatabaseCatalogPanel({ database }: { database: Database }) {
- const containerRef = useRef<HTMLDivElement>(null);
+const GRANT_ACCESS_PERMISSIONS: Permission[] = [
+ "bb.policies.createMaskingExemptionPolicy",
+ "bb.policies.updateMaskingExemptionPolicy",
+ "bb.databaseCatalogs.get",
+];
- useEffect(() => {
- if (!containerRef.current) {
- return;
+const flattenObjectSchema = (
+ parentPath: string,
+ objectSchema: ObjectSchema
+): {
+ column: string;
+ semanticTypeId: string;
+ target: ObjectSchema;
+}[] => {
+ switch (objectSchema.type) {
+ case ObjectSchema_Type.OBJECT: {
+ const result: {
+ column: string;
+ semanticTypeId: string;
+ target: ObjectSchema;
+ }[] = [];
+ if (objectSchema.kind?.case === "structKind") {
+ for (const [key, schema] of Object.entries(
+ objectSchema.kind.value.properties ?? {}
+ )) {
+ result.push(
+ ...flattenObjectSchema(
+ [parentPath, key].filter((item) => item).join("."),
+ schema
+ )
+ );
+ }
+ }
+ return result;
}
+ case ObjectSchema_Type.ARRAY:
+ if (
+ objectSchema.kind?.case === "arrayKind" &&
+ objectSchema.kind.value.kind
+ ) {
+ return flattenObjectSchema(parentPath, objectSchema.kind.value.kind);
+ }
+ return [];
+ default:
+ return [
+ {
+ column: parentPath,
+ semanticTypeId: objectSchema.semanticType,
+ target: objectSchema,
+ },
+ ];
+ }
+};
+
+const flattenSensitiveColumnList = (catalog?: DatabaseCatalog): MaskData[] => {
+ if (!catalog) {
+ return [];
+ }
- const app = createApp({
- render() {
- return h(
- NConfigProvider as never,
- { themeOverrides: themeOverrides.value },
- {
- default: () =>
- h(OverlayStackManager as never, null, {
- default: () =>
- h(DatabaseSensitiveDataPanel as never, {
- database,
- }),
- }),
+ const result: MaskData[] = [];
+
+ for (const schema of catalog.schemas) {
+ for (const table of schema.tables) {
+ if (table.kind?.case === "columns") {
+ for (const column of table.kind.value.columns ?? []) {
+ if (!column.semanticType && !column.classification) {
+ continue;
}
+ result.push({
+ schema: schema.name,
+ table: table.name,
+ column: column.name,
+ semanticTypeId: column.semanticType,
+ classificationId: column.classification,
+ target: column,
+ });
+ }
+ }
+
+ if (table.kind?.case === "objectSchema") {
+ const flattened = flattenObjectSchema("", table.kind.value);
+ result.push(
+ ...flattened.map((item) => ({
+ ...item,
+ schema: schema.name,
+ table: table.name,
+ classificationId: "",
+ disableClassification: true,
+ }))
);
- },
+ }
+
+ if (table.classification) {
+ result.push({
+ schema: schema.name,
+ table: table.name,
+ column: "",
+ semanticTypeId: "",
+ disableSemanticType: true,
+ classificationId: table.classification,
+ target: table,
+ });
+ }
+ }
+ }
+
+ return result;
+};
+
+const hasSemanticType = (
+ target: MaskDataTarget
+): target is ColumnCatalog | ObjectSchema => {
+ return "semanticType" in target;
+};
+
+const hasClassificationType = (
+ target: MaskDataTarget
+): target is ColumnCatalog | TableCatalog => {
+ return "classification" in target;
+};
+
+const itemKey = (item: MaskData) => {
+ return getMaskDataIdentifier(item);
+};
+
+export function DatabaseCatalogPanel({ database }: { database: Database }) {
+ const { t } = useTranslation();
+ const policyStore = usePolicyV1Store();
+ const databaseCatalogStore = useDatabaseCatalogV1Store();
+ const settingStore = useSettingV1Store();
+
+ const databaseCatalog = useDatabaseCatalog(database.name, false);
+ const catalog = useVueState(() => databaseCatalog.value);
+ const project = getDatabaseProject(database);
+ const instance = getInstanceResource(database);
+ const isMaskingForNoSQL = instanceV1MaskingForNoSQL(instance);
+ const hasUpdateCatalogPermission = hasProjectPermissionV2(
+ project,
+ "bb.databaseCatalogs.update"
+ );
+ const hasGrantAccessPermission = GRANT_ACCESS_PERMISSIONS.every(
+ (permission) => hasProjectPermissionV2(project, permission)
+ );
+
+ const semanticTypeList = useVueState(() => {
+ const setting = settingStore.getSettingByName(
+ Setting_SettingName.SEMANTIC_TYPES
+ );
+ return setting?.value?.value.case === "semanticType"
+ ? ((setting.value.value.value.types ??
+ []) as SemanticTypeSetting_SemanticType[])
+ : [];
+ });
+ const classificationConfig = useVueState(() =>
+ settingStore.getProjectClassification(
+ project.dataClassificationConfigId ?? ""
+ )
+ );
+ const hasSensitiveDataFeature = useVueState(
+ () => featureToRef(PlanFeature.FEATURE_DATA_MASKING, instance).value
+ );
+
+ const [searchText, setSearchText] = useState("");
+ const [checkedColumnList, setCheckedColumnList] = useState<MaskData[]>([]);
+ const [showFeatureDialog, setShowFeatureDialog] = useState(false);
+ const [showGrantAccessDialog, setShowGrantAccessDialog] = useState(false);
+ const [pendingDeleteItem, setPendingDeleteItem] = useState<MaskData | null>(
+ null
+ );
+
+ useEffect(() => {
+ void settingStore.getOrFetchSettingByName(
+ Setting_SettingName.SEMANTIC_TYPES,
+ true
+ );
+ void settingStore.getOrFetchSettingByName(
+ Setting_SettingName.DATA_CLASSIFICATION,
+ true
+ );
+ }, [settingStore]);
+
+ useEffect(() => {
+ setSearchText("");
+ setCheckedColumnList([]);
+ setShowFeatureDialog(false);
+ setShowGrantAccessDialog(false);
+ setPendingDeleteItem(null);
+ }, [database.name]);
+
+ const semanticTypeOptions = useMemo(
+ () =>
+ semanticTypeList.map((semanticType) => ({
+ label: semanticType.title || semanticType.id,
+ value: semanticType.id,
+ })),
+ [semanticTypeList]
+ );
+ const classificationOptions = useMemo(
+ () =>
+ Object.values(classificationConfig?.classification ?? {}).map(
+ (classification) => ({
+ label: classification.title || classification.id,
+ value: classification.id,
+ })
+ ),
+ [classificationConfig]
+ );
+ const columnList = useMemo(
+ () => flattenSensitiveColumnList(catalog),
+ [catalog]
+ );
+ const filteredColumnList = useMemo(() => {
+ const keyword = searchText.trim().toLowerCase();
+ if (!keyword) {
+ return columnList;
+ }
+ return columnList.filter((item) => {
+ return (
+ item.schema.toLowerCase().includes(keyword) ||
+ item.table.toLowerCase().includes(keyword) ||
+ item.column.toLowerCase().includes(keyword)
+ );
+ });
+ }, [columnList, searchText]);
+ const grantAccessColumnList = useMemo(
+ () =>
+ checkedColumnList.map((maskData) => ({
+ database,
+ maskData,
+ })),
+ [checkedColumnList, database]
+ );
+ const openGrantAccessDialog =
+ showGrantAccessDialog && checkedColumnList.length > 0;
+
+ const removeMaskingExceptions = async (sensitiveColumn: MaskData) => {
+ const policy = await policyStore.getOrFetchPolicyByParentAndType({
+ parentPath: database.project,
+ policyType: PolicyType.MASKING_EXEMPTION,
});
- app.use(router).use(pinia).use(i18n).use(NaiveUI);
- app.mount(containerRef.current);
+ if (!policy) {
+ return;
+ }
+
+ const exemptions = (
+ policy.policy?.case === "maskingExemptionPolicy"
+ ? policy.policy.value.exemptions
+ : []
+ ).filter(
+ (exception) =>
+ !isCurrentColumnException(exception, {
+ database,
+ maskData: sensitiveColumn,
+ })
+ );
- return () => {
- app.unmount();
+ policy.policy = {
+ case: "maskingExemptionPolicy",
+ value: create(MaskingExemptionPolicySchema, {
+ exemptions,
+ }),
};
- }, [database.name, database.project, database.environment]);
- return <div ref={containerRef} />;
+ await policyStore.upsertPolicy({
+ parentPath: database.project,
+ policy,
+ });
+ };
+
+ const handleDelete = async (item: MaskData) => {
+ setCheckedColumnList((current) =>
+ current.filter(
+ (selectedColumn) => itemKey(selectedColumn) !== itemKey(item)
+ )
+ );
+ if (hasSemanticType(item.target)) {
+ item.target.semanticType = "";
+ item.semanticTypeId = "";
+ }
+ if (hasClassificationType(item.target)) {
+ item.target.classification = "";
+ item.classificationId = "";
+ }
+ await databaseCatalogStore.updateDatabaseCatalog(catalog);
+ pushNotification({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t("common.removed"),
+ });
+ await removeMaskingExceptions(item);
+ };
+
+ const handleSemanticTypeChange = async (
+ item: MaskData,
+ semanticTypeId: string
+ ) => {
+ if (!hasSemanticType(item.target)) {
+ return;
+ }
+ item.target.semanticType = semanticTypeId;
+ item.semanticTypeId = semanticTypeId;
+ await databaseCatalogStore.updateDatabaseCatalog(catalog);
+ pushNotification({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t("common.updated"),
+ });
+ };
+
+ const handleClassificationChange = async (
+ item: MaskData,
+ classificationId: string
+ ) => {
+ if (!hasClassificationType(item.target)) {
+ return;
+ }
+ item.target.classification = classificationId;
+ item.classificationId = classificationId;
+ await databaseCatalogStore.updateDatabaseCatalog(catalog);
+ pushNotification({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t("common.updated"),
+ });
+ };
+
+ const handleGrantAccessClick = () => {
+ if (!hasSensitiveDataFeature) {
+ setShowFeatureDialog(true);
+ return;
+ }
+ setShowGrantAccessDialog(true);
+ };
+
+ const closeGrantAccessDialog = () => {
+ setShowGrantAccessDialog(false);
+ setCheckedColumnList([]);
+ };
+
+ const handleDeleteConfirmed = async () => {
+ if (!pendingDeleteItem) {
+ return;
+ }
+ const item = pendingDeleteItem;
+ setPendingDeleteItem(null);
+ await handleDelete(item);
+ };
+
+ return (
+ <div className="flex flex-col gap-y-4">
+ <FeatureAttention
+ feature={PlanFeature.FEATURE_DATA_MASKING}
+ instance={instance}
+ />
+
+ <div className="flex flex-wrap items-center justify-between gap-3">
+ <Input
+ value={searchText}
+ onChange={(event) => setSearchText(event.target.value)}
+ placeholder={t("common.search")}
+ className="w-full max-w-sm"
+ />
+
+ {!isMaskingForNoSQL && (
+ <PermissionGuard
+ permissions={GRANT_ACCESS_PERMISSIONS}
+ project={project}
+ >
+ {({ disabled }) => (
+ <Button
+ type="button"
+ className="w-full sm:w-auto"
+ disabled={
+ disabled ||
+ !hasGrantAccessPermission ||
+ checkedColumnList.length === 0
+ }
+ onClick={handleGrantAccessClick}
+ >
+ {hasSensitiveDataFeature ? (
+ <ShieldCheck className="w-4 h-4" />
+ ) : (
+ <FeatureBadge
+ feature={PlanFeature.FEATURE_DATA_MASKING}
+ instance={instance}
+ clickable={false}
+ className="text-white"
+ />
+ )}
+ {t("settings.sensitive-data.grant-access")}
+ </Button>
+ )}
+ </PermissionGuard>
+ )}
+ </div>
+
+ <SensitiveColumnTable
+ database={database}
+ columnList={filteredColumnList}
+ checkedColumnList={checkedColumnList}
+ showSelection={!isMaskingForNoSQL}
+ canEdit={hasUpdateCatalogPermission && hasSensitiveDataFeature}
+ showOperation={hasUpdateCatalogPermission && hasSensitiveDataFeature}
+ semanticTypeOptions={semanticTypeOptions}
+ classificationOptions={classificationOptions}
+ onCheckedColumnListChange={(columnList) =>
+ setCheckedColumnList(columnList)
+ }
+ onSemanticTypeChange={handleSemanticTypeChange}
+ onClassificationChange={handleClassificationChange}
+ onDelete={(item) => setPendingDeleteItem(item)}
+ />
+
+ <Dialog open={showFeatureDialog} onOpenChange={setShowFeatureDialog}>
+ <DialogContent className="p-6">
+ <DialogTitle>{t("common.warning")}</DialogTitle>
+ <div className="mt-3">
+ <FeatureAttention
+ feature={PlanFeature.FEATURE_DATA_MASKING}
+ instance={instance}
+ />
+ </div>
+ <div className="mt-6 flex justify-end gap-x-2">
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => setShowFeatureDialog(false)}
+ >
+ {t("common.cancel")}
+ </Button>
+ </div>
+ </DialogContent>
+ </Dialog>
+
+ <GrantAccessDialog
+ open={openGrantAccessDialog}
+ projectName={database.project}
+ columnList={grantAccessColumnList}
+ instance={instance}
+ onDismiss={closeGrantAccessDialog}
+ />
+
+ <AlertDialog
+ open={pendingDeleteItem !== null}
+ onOpenChange={(open) => {
+ if (!open) {
+ setPendingDeleteItem(null);
+ }
+ }}
+ >
+ <AlertDialogContent>
+ <AlertDialogTitle>{t("common.warning")}</AlertDialogTitle>
+ <AlertDialogDescription>
+ {t("settings.sensitive-data.remove-sensitive-column-tips")}
+ </AlertDialogDescription>
+ <div className="mt-4 flex flex-col gap-2 text-sm text-main">
+ {pendingDeleteItem ? (
+ <div className="rounded-xs border border-control-border px-3 py-2">
+ {pendingDeleteItem.schema
+ ? `${pendingDeleteItem.schema}.${pendingDeleteItem.table}`
+ : pendingDeleteItem.table}
+ {pendingDeleteItem.column ? `.${pendingDeleteItem.column}` : ""}
+ </div>
+ ) : null}
+ </div>
+ <AlertDialogFooter>
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => setPendingDeleteItem(null)}
+ >
+ {t("common.cancel")}
+ </Button>
+ <Button
+ type="button"
+ variant="destructive"
+ onClick={() => void handleDeleteConfirmed()}
+ >
+ {t("common.delete")}
+ </Button>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </div>
+ );
}