Skip to content

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

refactor(frontend): migrate masking exemption pages to React (#19868)

Danny Xu372ea486f52a
diff --git a/frontend/src/components/SensitiveData/ExemptionDetailPanel.vue b/frontend/src/components/SensitiveData/ExemptionDetailPanel.vue
deleted file mode 100644
index 300e3ad0f4..0000000000
--- a/frontend/src/components/SensitiveData/ExemptionDetailPanel.vue
+++ /dev/null
@@ -1,100 +0,0 @@
-<template>
- <div class="flex flex-col">
- <!-- Header -->
- <div class="px-4 pt-3 pb-1">
- <div class="flex items-center gap-x-2">
- <template v-if="member.type === 'group'">
- <GroupNameCell
- v-if="group"
- :group="group"
- :show-icon="false"
- :show-name="false"
- :show-member="false"
- :link="false"
- />
- <span v-else class="font-medium">{{ member.member }}</span>
- </template>
- <template v-else>
- <UserLink :title="userEmail" :email="userEmail" />
- </template>
- </div>
- <div class="mt-1 text-sm textinfolabel">
- {{ member.grants.length }}
- {{ $t("project.masking-exemption.self").toLowerCase() }}
- </div>
- </div>
-
- <!-- Grants as cards -->
- <div class="flex flex-col gap-y-3 px-4 pb-4">
- <div
- v-for="(grant, idx) in member.grants"
- :key="grant.id"
- class="border border-gray-200 rounded-lg overflow-hidden pt-4"
- >
- <ExemptionGrantSection
- :grant="grant"
- :disabled="disabled"
- :show-database-link="showDatabaseLink"
- :default-expanded="shouldExpand(idx)"
- @revoke="$emit('revoke', grant)"
- />
- </div>
- </div>
- </div>
-</template>
-
-<script lang="ts" setup>
-import { computed } from "vue";
-import GroupNameCell from "@/components/User/Settings/UserDataTableByGroup/cells/GroupNameCell.vue";
-import { UserLink } from "@/components/v2/Model/cells";
-import { extractUserEmail, useGroupStore } from "@/store";
-import { groupBindingPrefix } from "@/types";
-import ExemptionGrantSection from "./ExemptionGrantSection.vue";
-import type { ExemptionGrant, ExemptionMember } from "./types";
-
-const props = withDefaults(
- defineProps<{
- member: ExemptionMember;
- disabled: boolean;
- showDatabaseLink?: boolean;
- databaseFilter?: string;
- }>(),
- {
- showDatabaseLink: true,
- databaseFilter: undefined,
- }
-);
-
-defineEmits<{
- (e: "revoke", grant: ExemptionGrant): void;
-}>();
-
-const groupStore = useGroupStore(); // NOSONAR
-
-const userEmail = computed(() => extractUserEmail(props.member.member));
-
-const group = computed(() => {
- if (!props.member.member.startsWith(groupBindingPrefix)) return undefined;
- return groupStore.getGroupByIdentifier(props.member.member);
-});
-
-const grantMatchesFilter = (grant: ExemptionGrant): boolean => {
- if (!props.databaseFilter) return false;
- return (
- grant.databaseResources?.some(
- (r) => r.databaseFullName === props.databaseFilter
- ) ?? false
- );
-};
-
-const shouldExpand = (idx: number): boolean => {
- const grant = props.member.grants[idx];
- if (props.databaseFilter && grantMatchesFilter(grant)) {
- return true;
- }
- if (props.member.grants.length >= 3) {
- return idx === 0;
- }
- return true;
-};
-</script>
diff --git a/frontend/src/components/SensitiveData/ExemptionGrantSection.vue b/frontend/src/components/SensitiveData/ExemptionGrantSection.vue
deleted file mode 100644
index 150286e16b..0000000000
--- a/frontend/src/components/SensitiveData/ExemptionGrantSection.vue
+++ /dev/null
@@ -1,121 +0,0 @@
-<template>
- <NCollapse
- v-model:expanded-names="expandedNames"
- :theme-overrides="{
- dividerColor: 'transparent',
- titlePadding: '16px 16px',
- }"
- >
- <NCollapseItem :name="grant.id">
- <template #header>
- <div class="flex items-center gap-x-3">
- <span class="font-medium text-sm">
- {{ title }}
- </span>
- <template v-if="grant.expirationTimestamp && isExpired">
- <span class="text-xs text-control-light line-through">
- {{ dayjs(grant.expirationTimestamp).format("YYYY-MM-DD HH:mm") }}
- </span>
- <span class="text-xs text-control-light">
- ({{ $t("sql-editor.expired") }})
- </span>
- </template>
- <template v-else-if="grant.expirationTimestamp">
- <span class="text-xs font-medium text-blue-600">
- {{ expiryLabel }}
- </span>
- <span class="text-xs text-control-light">
- ({{ dayjs(grant.expirationTimestamp).format("YYYY-MM-DD HH:mm") }})
- </span>
- </template>
- <span
- v-else
- class="text-xs font-medium text-amber-600"
- >
- {{ $t("settings.sensitive-data.never-expires") }}
- </span>
- </div>
- </template>
- <template #header-extra>
- <NButton
- size="small"
- tertiary
- type="error"
- :disabled="disabled"
- @click.stop="$emit('revoke')"
- >
- {{ $t("common.revoke") }}
- </NButton>
- </template>
- <div class="px-4 pb-4 -mt-3">
- <!-- Reason -->
- <div class="mb-3 text-sm border-l-2 border-gray-300 pl-3 py-1 textinfolabel">
- <span class="font-medium text-gray-600">{{ $t("common.reason") }}:</span>
- {{ grant.description || $t("project.masking-exemption.no-reason") }}
- </div>
-
- <ExemptionResourceTable
- v-if="grant.databaseResources && grant.databaseResources.length > 0"
- :database-resources="grant.databaseResources"
- :classification-level="grant.classificationLevel"
- :show-database-link="showDatabaseLink"
- />
- <ExemptionLevelCard
- v-else
- :classification-level="grant.classificationLevel"
- />
- </div>
- </NCollapseItem>
- </NCollapse>
-</template>
-
-<script lang="ts" setup>
-import dayjs from "dayjs";
-import { NButton, NCollapse, NCollapseItem } from "naive-ui";
-import { computed, ref } from "vue";
-import { useI18n } from "vue-i18n";
-import ExemptionLevelCard from "./ExemptionLevelCard.vue";
-import ExemptionResourceTable from "./ExemptionResourceTable.vue";
-import { generateGrantTitle } from "./exemptionDataUtils";
-import type { ExemptionGrant } from "./types";
-
-const props = withDefaults(
- defineProps<{
- grant: ExemptionGrant;
- disabled: boolean;
- showDatabaseLink?: boolean;
- defaultExpanded?: boolean;
- }>(),
- {
- showDatabaseLink: true,
- defaultExpanded: true,
- }
-);
-
-defineEmits<{
- (e: "revoke"): void;
-}>();
-
-const { t } = useI18n(); // NOSONAR
-
-const title = computed(() => generateGrantTitle(props.grant));
-
-const isExpired = computed(
- () =>
- !!props.grant.expirationTimestamp &&
- props.grant.expirationTimestamp <= Date.now()
-);
-
-const expiryLabel = computed(() => {
- if (!props.grant.expirationTimestamp) return "";
- const msRemaining = props.grant.expirationTimestamp - Date.now();
- const hoursRemaining = msRemaining / (1000 * 60 * 60);
- if (hoursRemaining < 24) return t("project.masking-exemption.expires-today");
- const days = Math.ceil(hoursRemaining / 24);
- return t("project.masking-exemption.expires-in-days", { days }, days);
-});
-
-const expandedNames = ref<string[]>(
- props.defaultExpanded ? [props.grant.id] : []
-);
-</script>
diff --git a/frontend/src/components/SensitiveData/ExemptionLevelCard.vue b/frontend/src/components/SensitiveData/ExemptionLevelCard.vue
deleted file mode 100644
index f3a4b6e54b..0000000000
--- a/frontend/src/components/SensitiveData/ExemptionLevelCard.vue
+++ /dev/null
@@ -1,32 +0,0 @@
-<template>
- <div
- class="flex items-center gap-x-6 px-4 py-3 bg-gray-50 rounded border border-gray-200"
- >
- <div class="flex items-center gap-x-2">
- <span class="textinfolabel font-medium uppercase text-xs">{{ $t("common.scope") }}</span>
- <span
- class="px-2 py-0.5 rounded text-xs bg-green-100 text-green-700 border border-green-200"
- >
- {{ $t("database.all") }}
- </span>
- </div>
- <div class="flex items-center gap-x-2">
- <span class="textinfolabel font-medium uppercase text-xs">{{ $t("common.classification-level") }}</span>
- <LevelBadge
- v-if="classificationLevel"
- :level="classificationLevel.value"
- :operator="classificationLevel.operator"
- />
- <LevelBadge v-else :no-limit="true" />
- </div>
- </div>
-</template>
-
-<script lang="ts" setup>
-import LevelBadge from "./LevelBadge.vue";
-import type { ClassificationLevel } from "./types";
-
-defineProps<{
- classificationLevel?: ClassificationLevel;
-}>();
-</script>
diff --git a/frontend/src/components/SensitiveData/ExemptionMemberItem.vue b/frontend/src/components/SensitiveData/ExemptionMemberItem.vue
deleted file mode 100644
index a238f657fb..0000000000
--- a/frontend/src/components/SensitiveData/ExemptionMemberItem.vue
+++ /dev/null
@@ -1,137 +0,0 @@
-<template>
- <div
- class="flex items-center gap-x-3 px-3 py-2.5 cursor-pointer rounded transition-colors"
- :class="selected ? 'bg-blue-50' : 'hover:bg-gray-50'"
- @click="handleClick"
- >
- <!-- Chevron for expandable mode -->
- <ChevronRightIcon
- v-if="expandable"
- class="w-4 h-4 shrink-0 text-control-placeholder transition-transform"
- :class="expanded ? 'rotate-90' : ''"
- />
-
- <!-- Avatar -->
- <BBAvatar
- :username="displayName"
- :email="member.type === 'user' ? userEmail : ''"
- size="SMALL"
- />
-
- <!-- Content -->
- <div class="flex-1 min-w-0">
- <!-- Line 1: Name -->
- <div class="flex items-center gap-x-1.5">
- <span class="font-medium text-sm truncate">{{ displayName }}</span>
- <NTag
- v-if="member.type === 'group'"
- size="small"
- round
- >
- {{ $t("common.groups") }}
- </NTag>
- <NTag
- v-else-if="isServiceAccount"
- size="small"
- round
- type="info"
- >
- {{ $t("settings.members.service-account") }}
- </NTag>
- <NTag
- v-else-if="isWorkloadIdentity"
- size="small"
- round
- type="info"
- >
- {{ $t("settings.members.workload-identity") }}
- </NTag>
- </div>
-
- <!-- Line 2: Scope summary -->
- <div class="text-xs text-control-light truncate mt-0.5">
- {{ scopeSummary }}
- </div>
-
- </div>
- </div>
-</template>
-
-<script lang="ts" setup>
-import { ChevronRightIcon } from "lucide-vue-next";
-import { NTag } from "naive-ui";
-import { computed } from "vue";
-import { useI18n } from "vue-i18n";
-import { BBAvatar } from "@/bbkit";
-import { extractUserEmail } from "@/store";
-import {
- serviceAccountBindingPrefix,
- workloadIdentityBindingPrefix,
-} from "@/types";
-import type { ExemptionMember } from "./types";
-
-const { t: $t } = useI18n(); // NOSONAR
-
-const props = withDefaults(
- defineProps<{
- member: ExemptionMember;
- selected?: boolean;
- expanded?: boolean;
- expandable?: boolean;
- }>(),
- {
- selected: false,
- expanded: false,
- expandable: false,
- }
-);
-
-const emit = defineEmits<{
- (e: "select"): void;
- (e: "toggle"): void;
-}>();
-
-const userEmail = computed(() => extractUserEmail(props.member.member));
-
-const isServiceAccount = computed(() =>
- props.member.member.startsWith(serviceAccountBindingPrefix)
-);
-
-const isWorkloadIdentity = computed(() =>
- props.member.member.startsWith(workloadIdentityBindingPrefix)
-);
-
-const displayName = computed(() => {
- // Strip prefix (user:, group:, serviceAccount:, workloadIdentity:) to show just the email/name
- const raw = props.member.member;
- const idx = raw.indexOf(":");
- return idx >= 0 ? raw.substring(idx + 1) : raw;
-});
-
-const scopeSummary = computed(() => {
- const n = props.member.grants.length;
- const exemptionWord = $t("project.masking-exemption.n-exemptions", { n }, n);
-
- const realDbs = props.member.databaseNames.filter((name) => name !== "");
- const hasAllDbs = props.member.databaseNames.includes("");
-
- const parts: string[] = [];
- if (realDbs.length > 0) {
- parts.push(realDbs.join(", "));
- }
- if (hasAllDbs) {
- parts.push($t("database.all"));
- }
-
- const scope = parts.join(", ");
- return scope ? `${exemptionWord} · ${scope}` : exemptionWord;
-});
-
-const handleClick = () => {
- if (props.expandable) {
- emit("toggle");
- } else {
- emit("select");
- }
-};
-</script>
diff --git a/frontend/src/components/SensitiveData/ExemptionMemberList.vue b/frontend/src/components/SensitiveData/ExemptionMemberList.vue
deleted file mode 100644
index 930ac595a2..0000000000
--- a/frontend/src/components/SensitiveData/ExemptionMemberList.vue
+++ /dev/null
@@ -1,105 +0,0 @@
-<template>
- <div class="overflow-y-auto">
- <div
- v-if="loading"
- class="flex items-center justify-center py-12"
- >
- <NSpin size="small" />
- </div>
- <template v-else-if="members.length > 0">
- <div class="divide-y divide-gray-100">
- <div v-for="member in members" :key="member.member">
- <ExemptionMemberItem
- :member="member"
- :selected="!expandable && effectiveSelectedKey === member.member"
- :expandable="expandable"
- :expanded="expandable && expandedMemberKey === member.member"
- @select="handleSelect(member)"
- @toggle="handleToggle(member)"
- />
- <!-- Inline detail panel in narrow/expandable mode -->
- <div
- v-if="expandable && expandedMemberKey === member.member"
- class="border-t border-b border-gray-200"
- >
- <ExemptionDetailPanel
- :member="member"
- :disabled="disabled"
- :show-database-link="showDatabaseLink"
- :database-filter="databaseFilter"
- @revoke="(grant) => $emit('revoke', member, grant)"
- />
- </div>
- </div>
- </div>
- </template>
- <div
- v-else
- class="flex items-center justify-center py-12 text-control-placeholder text-sm"
- >
- {{ $t("project.masking-exemption.no-exemptions") }}
- </div>
- </div>
-</template>
-
-<script lang="ts" setup>
-import { NSpin } from "naive-ui";
-import { computed, ref, watch } from "vue";
-import ExemptionDetailPanel from "./ExemptionDetailPanel.vue";
-import ExemptionMemberItem from "./ExemptionMemberItem.vue";
-import type { ExemptionGrant, ExemptionMember } from "./types";
-
-const props = withDefaults(
- defineProps<{
- members: ExemptionMember[];
- disabled: boolean;
- loading?: boolean;
- expandable?: boolean;
- showDatabaseLink?: boolean;
- databaseFilter?: string;
- selectedMemberKey?: string;
- }>(),
- {
- loading: false,
- expandable: false,
- showDatabaseLink: true,
- databaseFilter: undefined,
- selectedMemberKey: "",
- }
-);
-
-const emit = defineEmits<{
- (e: "select", memberKey: string): void;
- (e: "revoke", member: ExemptionMember, grant: ExemptionGrant): void;
-}>();
-
-const expandedMemberKey = ref("");
-
-// In wide mode, use the parent-controlled prop as the source of truth.
-const effectiveSelectedKey = computed(() => props.selectedMemberKey);
-
-const handleSelect = (member: ExemptionMember) => {
- emit("select", member.member);
-};
-
-const handleToggle = (member: ExemptionMember) => {
- expandedMemberKey.value =
- expandedMemberKey.value === member.member ? "" : member.member;
-};
-
-// Auto-select first member in wide mode
-watch(
- () => props.members,
- (members) => {
- if (!props.expandable && members.length > 0) {
- if (
- !props.selectedMemberKey ||
- !members.some((m) => m.member === props.selectedMemberKey)
- ) {
- emit("select", members[0].member);
- }
- }
- },
- { immediate: true }
-);
-</script>
diff --git a/frontend/src/components/SensitiveData/ExemptionPresetTabs.vue b/frontend/src/components/SensitiveData/ExemptionPresetTabs.vue
deleted file mode 100644
index 45ea23c094..0000000000
--- a/frontend/src/components/SensitiveData/ExemptionPresetTabs.vue
+++ /dev/null
@@ -1,55 +0,0 @@
-<template>
- <div class="shrink-0">
- <NTabs
- :value="activePreset"
- type="line"
- size="small"
- @update:value="selectPreset"
- >
- <NTab
- v-for="preset in presets"
- :key="preset.id"
- :name="preset.id"
- >
- {{ preset.label }}
- </NTab>
- </NTabs>
- </div>
-</template>
-
-<script lang="ts" setup>
-import { NTab, NTabs } from "naive-ui";
-import { computed } from "vue";
-import { useI18n } from "vue-i18n";
-import type { SearchParams } from "@/utils";
-import { getValueFromSearchParams, upsertScope } from "@/utils";
-
-const props = defineProps<{
- params: SearchParams;
-}>();
-
-const emit = defineEmits<{
- (e: "update:params", params: SearchParams): void;
-}>();
-
-const { t } = useI18n(); // NOSONAR
-
-const presets = computed(() => [
- { id: "active", label: t("common.active") },
- { id: "expired", label: t("sql-editor.expired") },
- { id: "all", label: t("common.all") },
-]);
-
-const activePreset = computed(() => {
- const status = getValueFromSearchParams(props.params, "status");
- return status || "active";
-});
-
-const selectPreset = (id: string) => {
- const updated = upsertScope({
- params: props.params,
- scopes: { id: "status", value: id },
- });
- emit("update:params", updated);
-};
-</script>
diff --git a/frontend/src/components/SensitiveData/ExemptionResourceTable.vue b/frontend/src/components/SensitiveData/ExemptionResourceTable.vue
deleted file mode 100644
index c6175a350d..0000000000
--- a/frontend/src/components/SensitiveData/ExemptionResourceTable.vue
+++ /dev/null
@@ -1,197 +0,0 @@
-<template>
- <div>
- <div class="overflow-x-auto">
- <table class="w-full text-sm table-fixed min-w-[600px]">
- <colgroup>
- <col style="width: 16%" />
- <col style="width: 16%" />
- <col style="width: 14%" />
- <col style="width: 18%" />
- <col style="width: 20%" />
- <col style="width: 16%" />
- </colgroup>
- <thead>
- <tr class="border-b border-gray-200">
- <th class="textinfolabel font-medium uppercase text-xs tracking-wider py-2 px-2 text-left">
- {{ $t("common.instance") }}
- </th>
- <th class="textinfolabel font-medium uppercase text-xs tracking-wider py-2 px-2 text-left">
- {{ $t("common.database") }}
- </th>
- <th class="textinfolabel font-medium uppercase text-xs tracking-wider py-2 px-2 text-left">
- {{ $t("common.schema") }}
- </th>
- <th class="textinfolabel font-medium uppercase text-xs tracking-wider py-2 px-2 text-left">
- {{ $t("common.table") }}
- </th>
- <th class="textinfolabel font-medium uppercase text-xs tracking-wider py-2 px-2 text-left">
- {{ $t("database.columns") }}
- </th>
- <th class="textinfolabel font-medium uppercase text-xs tracking-wider py-2 px-2 text-left">
- {{ $t("common.classification-level") }}
- </th>
- </tr>
- </thead>
- <tbody>
- <tr
- v-for="(resource, idx) in databaseResources"
- :key="idx"
- class="border-b border-gray-200 last:border-b-0"
- >
- <td class="py-2 px-2 text-control-light">
- <NTooltip>
- <template #trigger>
- <span class="block truncate">{{ displayInstance(resource) }}</span>
- </template>
- {{ displayInstance(resource) }}
- </NTooltip>
- </td>
- <td class="py-2 px-2">
- <span v-if="isSentinel(extractDatabaseResourceName(resource.databaseFullName).databaseName)" class="text-control-placeholder">
- {{ $t("database.all") }}
- </span>
- <NTooltip v-else-if="props.showDatabaseLink">
- <template #trigger>
- <span
- class="block truncate normal-link cursor-pointer"
- @click="handleDatabaseClick(resource)"
- >
- {{ extractDatabaseResourceName(resource.databaseFullName).databaseName }}
- </span>
- </template>
- {{ extractDatabaseResourceName(resource.databaseFullName).databaseName }}
- </NTooltip>
- <NTooltip v-else>
- <template #trigger>
- <span class="block truncate text-control-light">
- {{ extractDatabaseResourceName(resource.databaseFullName).databaseName }}
- </span>
- </template>
- {{ extractDatabaseResourceName(resource.databaseFullName).databaseName }}
- </NTooltip>
- </td>
- <td class="py-2 px-2 text-control-light">
- <NTooltip v-if="resource.schema">
- <template #trigger>
- <span class="block truncate">{{ resource.schema }}</span>
- </template>
- {{ resource.schema }}
- </NTooltip>
- <span v-else>-</span>
- </td>
- <td class="py-2 px-2 text-control-light">
- <NTooltip v-if="resource.table">
- <template #trigger>
- <span class="block truncate">{{ resource.table }}</span>
- </template>
- {{ resource.table }}
- </NTooltip>
- <span v-else>-</span>
- </td>
- <td class="py-2 px-2">
- <ColumnCell :columns="resource.columns" />
- </td>
- <td class="py-2 px-2">
- <LevelBadge
- v-if="classificationLevel"
- :level="classificationLevel.value"
- :operator="classificationLevel.operator"
- />
- <LevelBadge v-else :no-limit="true" />
- </td>
- </tr>
- </tbody>
- </table>
- </div>
- </div>
-</template>
-
-<script lang="ts" setup>
-import { NTooltip } from "naive-ui";
-import { defineComponent, h } from "vue";
-import { useI18n } from "vue-i18n";
-import { useRouter } from "vue-router";
-import type { DatabaseResource } from "@/types";
-import { extractDatabaseResourceName } from "@/utils";
-import LevelBadge from "./LevelBadge.vue";
-import type { ClassificationLevel } from "./types";
-
-const { t: $t } = useI18n(); // NOSONAR
-const router = useRouter(); // NOSONAR
-
-const COLUMN_VISIBLE_LIMIT = 3;
-
-const props = withDefaults(
- defineProps<{
- databaseResources: DatabaseResource[];
- classificationLevel?: ClassificationLevel;
- showDatabaseLink?: boolean;
- }>(),
- {
- classificationLevel: undefined,
- showDatabaseLink: true,
- }
-);
-
-function isSentinel(value: string): boolean {
- return value === "";
-}
-
-function displayInstance(resource: DatabaseResource): string {
- const { instanceName } = extractDatabaseResourceName(
- resource.databaseFullName
- );
- return isSentinel(instanceName) ? $t("database.all") : instanceName;
-}
-
-function handleDatabaseClick(resource: DatabaseResource) {
- const path = resource.databaseFullName.startsWith("/")
- ? resource.databaseFullName
- : `/${resource.databaseFullName}`;
- router.push(path);
-}
-
-// Render-function component for columns cell with tooltip
-const ColumnCell = defineComponent({
- props: {
- columns: {
- type: Array as () => string[] | undefined,
- default: undefined,
- },
- },
- setup(props) {
- return () => {
- const cols = props.columns;
- if (!cols || cols.length === 0) {
- return h("span", { class: "text-control-placeholder" }, "-");
- }
- const visible = cols.slice(0, COLUMN_VISIBLE_LIMIT);
- const rest = cols.length - visible.length;
- const text = visible.join(", ");
-
- if (rest <= 0) {
- return h("span", { class: "text-control-light" }, text);
- }
-
- const trigger = h("span", { class: "text-control-light" }, [
- text,
- h(
- "span",
- { class: "text-control-placeholder ml-1" },
- $t("common.n-more", { n: rest })
- ),
- ]);
-
- return h(NTooltip, null, {
- trigger: () => trigger,
- default: () =>
- h(
- "div",
- { class: "flex flex-col gap-y-0.5" },
- cols.map((col) => h("span", null, col))
- ),
- });
- };
- },
-});
-</script>
diff --git a/frontend/src/components/SensitiveData/ExemptionSearchBar.vue b/frontend/src/components/SensitiveData/ExemptionSearchBar.vue
deleted file mode 100644
index 18df5ca318..0000000000
--- a/frontend/src/components/SensitiveData/ExemptionSearchBar.vue
+++ /dev/null
@@ -1,32 +0,0 @@
-<template>
- <AdvancedSearch
- v-model:params="localParams"
- :scope-options="scopeOptions"
- :placeholder="$t('issue.advanced-search.self')"
- :autofocus="false"
- />
-</template>
-
-<script lang="ts" setup>
-import { computed } from "vue";
-import AdvancedSearch from "@/components/AdvancedSearch";
-import type { SearchParams } from "@/utils";
-import { useExemptionSearchScopeOptions } from "./useExemptionSearchScopeOptions";
-
-const props = defineProps<{
- params: SearchParams;
- projectName: string;
-}>();
-
-const emit = defineEmits<{
- (e: "update:params", params: SearchParams): void;
-}>();
-
-const projectNameRef = computed(() => props.projectName);
-const scopeOptions = useExemptionSearchScopeOptions(projectNameRef); // NOSONAR
-
-const localParams = computed({
- get: () => props.params,
- set: (val) => emit("update:params", val),
-});
-</script>
diff --git a/frontend/src/components/SensitiveData/LevelBadge.vue b/frontend/src/components/SensitiveData/LevelBadge.vue
deleted file mode 100644
index 250a8d18f6..0000000000
--- a/frontend/src/components/SensitiveData/LevelBadge.vue
+++ /dev/null
@@ -1,62 +0,0 @@
-<template>
- <span :class="['px-1 py-0.5 rounded text-xs whitespace-nowrap', colorClass]">
- {{ label }}
- </span>
-</template>
-
-<script lang="ts" setup>
-import { computed } from "vue";
-import { useI18n } from "vue-i18n";
-import { operatorDisplayLabel } from "@/plugins/cel/types/operator";
-import { useSettingV1Store } from "@/store";
-
-const { t } = useI18n(); // NOSONAR: Vue composable, not React hook
-
-const props = withDefaults(
- defineProps<{
- level?: number;
- operator?: string;
- noLimit?: boolean;
- }>(),
- {
- level: undefined,
- operator: "<=",
- noLimit: false,
- }
-);
-
-const settingStore = useSettingV1Store(); // NOSONAR
-
-const levelTitle = computed(() => {
- if (props.level === undefined) return undefined;
- const config = settingStore.classification[0];
- return config?.levels?.find((l) => l.level === props.level)?.title;
-});
-
-// Color mapping follows ClassificationLevelBadge.vue
-const bgColorList = [
- "bg-green-200", // level 1
- "bg-yellow-200", // level 2
- "bg-orange-300", // level 3
- "bg-amber-500", // level 4
- "bg-red-500", // level 5+
-];
-
-const label = computed(() => {
- if (props.noLimit) return t("project.masking-exemption.all-levels");
- if (props.level === undefined)
- return t("project.masking-exemption.all-levels");
- const op = operatorDisplayLabel(props.operator);
- const title = levelTitle.value;
- return title ? `${op} ${props.level} (${title})` : `${op} ${props.level}`;
-});
-
-const colorClass = computed(() => {
- if (props.noLimit || props.level === undefined) {
- return "bg-gray-200 text-gray-600";
- }
- const idx = Math.min(props.level - 1, bgColorList.length - 1);
- const bg = bgColorList[Math.max(0, idx)] ?? "bg-gray-200";
- return props.level >= 4 ? `${bg} text-white` : bg;
-});
-</script>
diff --git a/frontend/src/components/SensitiveData/useExemptionData.ts b/frontend/src/components/SensitiveData/useExemptionData.ts
deleted file mode 100644
index ec61196210..0000000000
--- a/frontend/src/components/SensitiveData/useExemptionData.ts
+++ /dev/null
@@ -1,258 +0,0 @@
-import { create } from "@bufbuild/protobuf";
-import type { ComputedRef } from "vue";
-import { computed, reactive, watch } from "vue";
-import { useI18n } from "vue-i18n";
-import {
- composePolicyBindings,
- pushNotification,
- useGroupStore,
- usePolicyByParentAndType,
- usePolicyV1Store,
- useSettingV1Store,
-} from "@/store";
-import { groupBindingPrefix } from "@/types";
-import { ExprSchema } from "@/types/proto-es/google/type/expr_pb";
-import type { MaskingExemptionPolicy_Exemption } from "@/types/proto-es/v1/org_policy_service_pb";
-import {
- MaskingExemptionPolicySchema,
- PolicyType,
-} from "@/types/proto-es/v1/org_policy_service_pb";
-import { Setting_SettingName } from "@/types/proto-es/v1/setting_service_pb";
-import {
- batchConvertFromCELString,
- type ConditionExpression,
-} from "@/utils/issue/cel";
-import {
- getConditionExpression,
- groupByMember,
- parseExpirationTimestamp,
-} from "./exemptionDataUtils";
-import type { AccessUser, ExemptionGrant, ExemptionMember } from "./types";
-
-interface LocalState {
- loading: boolean;
- processing: boolean;
- rawAccessList: AccessUser[];
-}
-
-function getAccessUsers(
- exemption: MaskingExemptionPolicy_Exemption,
- condition: ConditionExpression
-): AccessUser[] {
- const expression = exemption.condition?.expression ?? "";
- const description = exemption.condition?.description ?? "";
- const expirationTimestamp = parseExpirationTimestamp(expression);
- const conditionExpression = getConditionExpression(expression);
-
- return exemption.members.map((member) => ({
- type: member.startsWith(groupBindingPrefix)
- ? ("group" as const)
- : ("user" as const),
- member,
- expirationTimestamp,
- rawExpression: expression,
- description,
- databaseResources:
- condition.databaseResources && condition.databaseResources.length > 0
- ? condition.databaseResources
- : undefined,
- conditionExpression,
- }));
-}
-
-function rebuildExemptions(accessList: AccessUser[]) {
- const expressionsMap = new Map<
- string,
- { description: string; members: string[] }
- >();
-
- for (const accessUser of accessList) {
- const expressions = accessUser.rawExpression.split(" && ").filter((e) => e);
- const index = expressions.findIndex((exp) =>
- exp.startsWith("request.time")
- );
- if (index >= 0) {
- if (!accessUser.expirationTimestamp) {
- expressions.splice(index, 1);
- } else {
- expressions[index] = `request.time < timestamp("${new Date(
- accessUser.expirationTimestamp
- ).toISOString()}")`;
- }
- } else if (accessUser.expirationTimestamp) {
- expressions.push(
- `request.time < timestamp("${new Date(
- accessUser.expirationTimestamp
- ).toISOString()}")`
- );
- }
- const finalExpression = expressions.join(" && ");
- if (!expressionsMap.has(finalExpression)) {
- expressionsMap.set(finalExpression, {
- description: accessUser.description,
- members: [],
- });
- }
- expressionsMap.get(finalExpression)!.members.push(accessUser.member);
- }
-
- const exemptions = [];
- for (const [expression, { description, members }] of expressionsMap) {
- exemptions.push({
- members,
- condition: create(ExprSchema, { description, expression }),
- });
- }
- return exemptions;
-}
-
-export function useExemptionData(projectName: ComputedRef<string>) {
- const { t } = useI18n();
- // Ensure group store is initialized for composePolicyBindings
- useGroupStore();
- const policyStore = usePolicyV1Store();
- // Ensure classification config is loaded so LevelBadge can resolve level names
- const settingStore = useSettingV1Store();
- settingStore.getOrFetchSettingByName(
- Setting_SettingName.DATA_CLASSIFICATION,
- true
- );
-
- const state = reactive<LocalState>({
- loading: true,
- processing: false,
- rawAccessList: [],
- });
-
- const { policy, ready } = usePolicyByParentAndType(
- computed(() => ({
- parentPath: projectName.value,
- policyType: PolicyType.MASKING_EXEMPTION,
- }))
- );
-
- let fetchGeneration = 0;
-
- const updateAccessUserList = async () => {
- if (!ready.value) {
- return;
- }
-
- if (
- !policy.value ||
- policy.value.policy?.case !== "maskingExemptionPolicy"
- ) {
- state.rawAccessList = [];
- state.loading = false;
- return;
- }
-
- state.loading = true;
-
- const generation = ++fetchGeneration;
- try {
- const memberMap = new Map<string, AccessUser>();
- const { exemptions } = policy.value.policy.value;
- const expressionList = exemptions.map((e) =>
- e.condition?.expression ? e.condition.expression : "true"
- );
- const conditionList = await batchConvertFromCELString(expressionList);
-
- // A newer fetch was started — discard this stale result.
- if (generation !== fetchGeneration) return;
-
- await composePolicyBindings(exemptions, true);
- for (let i = 0; i < exemptions.length; i++) {
- const exemption = exemptions[i];
- const condition = conditionList[i];
- const expr = exemption.condition?.expression ?? "";
- const desc = exemption.condition?.description ?? "";
- for (const item of getAccessUsers(exemption, condition)) {
- const uniqueKey = `${item.member}:${expr}.${desc}:${i}`;
- memberMap.set(uniqueKey, item);
- }
- }
-
- // Final staleness check after all async work.
- if (generation !== fetchGeneration) return;
-
- state.rawAccessList = [...memberMap.values()];
- } finally {
- if (generation === fetchGeneration) {
- state.loading = false;
- }
- }
- };
-
- watch([ready, () => policy.value], () => updateAccessUserList(), {
- immediate: true,
- });
-
- const members = computed<ExemptionMember[]>(() =>
- groupByMember(state.rawAccessList)
- );
-
- const upsertPolicy = async () => {
- const pol = await policyStore.getOrFetchPolicyByParentAndType({
- parentPath: projectName.value,
- policyType: PolicyType.MASKING_EXEMPTION,
- });
- if (!pol) return;
-
- pol.policy = {
- case: "maskingExemptionPolicy",
- value: create(MaskingExemptionPolicySchema, {
- exemptions: rebuildExemptions(state.rawAccessList),
- }),
- };
- await policyStore.upsertPolicy({
- parentPath: projectName.value,
- policy: pol,
- });
- };
-
- const submit = async () => {
- if (state.processing) return;
- state.processing = true;
- try {
- await upsertPolicy();
- pushNotification({
- module: "bytebase",
- style: "SUCCESS",
- title: t("common.updated"),
- });
- } finally {
- state.processing = false;
- }
- };
-
- const revokeGrant = async (
- member: ExemptionMember,
- grant: ExemptionGrant
- ) => {
- // Remove only the first matching AccessUser to avoid over-removing when
- // duplicate exemptions exist (same member + expression + description).
- const idx = state.rawAccessList.findIndex(
- (a) =>
- a.member === member.member &&
- a.rawExpression === grant.rawExpression &&
- (a.description || "") === grant.description
- );
- if (idx < 0) return;
- const [removed] = state.rawAccessList.splice(idx, 1);
- try {
- await submit();
- } catch {
- // Restore on failure so UI stays in sync with backend
- state.rawAccessList.splice(idx, 0, removed);
- }
- };
-
- const loading = computed(() => !ready.value || state.loading);
-
- return {
- members,
- loading,
- revokeGrant,
- };
-}
diff --git a/frontend/src/components/SensitiveData/useExemptionSearchScopeOptions.ts b/frontend/src/components/SensitiveData/useExemptionSearchScopeOptions.ts
deleted file mode 100644
index 6325f4b22f..0000000000
--- a/frontend/src/components/SensitiveData/useExemptionSearchScopeOptions.ts
+++ /dev/null
@@ -1,73 +0,0 @@
-import type { ComputedRef } from "vue";
-import { computed, h } from "vue";
-import type {
- ScopeOption,
- ValueOption,
-} from "@/components/AdvancedSearch/types";
-import { RichDatabaseName } from "@/components/v2";
-import { t } from "@/plugins/i18n";
-import { useDatabaseV1Store } from "@/store";
-import { getDefaultPagination } from "@/utils";
-import { extractDatabaseResourceName } from "@/utils/v1/database";
-
-export function useExemptionSearchScopeOptions(
- projectName: ComputedRef<string>
-): ComputedRef<ScopeOption[]> {
- const databaseStore = useDatabaseV1Store();
-
- return computed((): ScopeOption[] => {
- return [
- {
- id: "database",
- title: t("common.database"),
- search: ({ keyword, nextPageToken: pageToken }) =>
- databaseStore
- .fetchDatabases({
- parent: projectName.value,
- pageToken: pageToken,
- pageSize: getDefaultPagination(),
- filter: { query: keyword },
- })
- .then((resp) => ({
- nextPageToken: resp.nextPageToken,
- options: resp.databases.map<ValueOption>((db) => {
- const { database: dbName } = extractDatabaseResourceName(
- db.name
- );
- return {
- value: db.name,
- keywords: [dbName, db.name],
- custom: true,
- render: () =>
- h(RichDatabaseName, {
- database: db,
- showInstance: true,
- showEngineIcon: true,
- }),
- };
- }),
- })),
- },
- {
- id: "member",
- title: t("common.members", 1),
- },
- {
- id: "status",
- title: t("common.status"),
- options: [
- {
- value: "active",
- keywords: ["active"],
- render: () => t("common.active"),
- },
- {
- value: "expired",
- keywords: ["expired"],
- render: () => t("sql-editor.expired"),
- },
- ],
- },
- ];
- });
-}
diff --git a/frontend/src/layouts/ProjectV1Layout.vue b/frontend/src/layouts/ProjectV1Layout.vue
index 5f5ea58b5e..674dc2f7bd 100644
--- a/frontend/src/layouts/ProjectV1Layout.vue
+++ b/frontend/src/layouts/ProjectV1Layout.vue
@@ -73,13 +73,32 @@ const { remove: removeVisit } = useRecentVisit();
const projectName = computed(() => `${projectNamePrefix}${props.projectId}`);
watchEffect(async () => {
+ // Capture the current project name before the async gap so we can
+ // detect stale responses if projectId changes while the fetch is
+ // in flight.
+ const currentName = projectName.value;
try {
const project = await projectStore.getOrFetchProjectByName(
- projectName.value,
+ currentName,
false
);
+ // If projectId changed during the fetch, ignore this stale result.
+ if (currentName !== projectName.value) return;
+ // If the project resolves to the unknown sentinel (e.g. projectId is "-1"),
+ // it will never initialize. Redirect to the landing page instead of
+ // spinning forever.
+ if (project.name === UNKNOWN_PROJECT_NAME) {
+ const projectRoute = router.resolve({
+ name: PROJECT_V1_ROUTE_DETAIL,
+ params: { projectId: props.projectId },
+ });
+ removeVisit(projectRoute.fullPath);
+ router.replace({ name: WORKSPACE_ROUTE_LANDING });
+ return;
+ }
recentProjects.setRecentProject(project.name);
} catch (err) {
+ if (currentName !== projectName.value) return;
console.error(err);
pushNotification({
module: "bytebase",
diff --git a/frontend/src/react/ReactPageMount.vue b/frontend/src/react/ReactPageMount.vue
index 83fd12a1b1..54e771f937 100644
--- a/frontend/src/react/ReactPageMount.vue
+++ b/frontend/src/react/ReactPageMount.vue
@@ -23,6 +23,8 @@ const pageProps = computed(() => {
return Object.keys(a).length > 0 ? { ...a } : undefined;
});
+let currentPage = "";
+
async function render() {
if (!container.value) return;
const [{ mountReactPage, updateReactPage }, i18nModule] = await Promise.all([
@@ -32,11 +34,18 @@ async function render() {
if (i18nModule.default.language !== locale.value) {
await i18nModule.default.changeLanguage(locale.value);
}
+ // When the page component changes, unmount old root and create a fresh one
+ // to avoid stale React state from the previous page.
+ if (root && currentPage !== props.page) {
+ root.unmount();
+ root = null;
+ }
if (!root) {
root = await mountReactPage(container.value, props.page, pageProps.value);
} else {
await updateReactPage(root, props.page, pageProps.value);
}
+ currentPage = props.page;
}
onMounted(() => render());
diff --git a/frontend/src/react/components/ui/expiration-picker.tsx b/frontend/src/react/components/ui/expiration-picker.tsx
new file mode 100644
index 0000000000..95f510bec9
--- /dev/null
+++ b/frontend/src/react/components/ui/expiration-picker.tsx
@@ -0,0 +1,42 @@
+import { X } from "lucide-react";
+import { useTranslation } from "react-i18next";
+
+/**
+ * ExpirationPicker — a datetime picker with inline clear button.
+ *
+ * Value format: "YYYY-MM-DDTHH:mm" (datetime-local compatible) or undefined
+ * for "never expires".
+ */
+export function ExpirationPicker({
+ value,
+ onChange,
+ minDate,
+}: {
+ value: string | undefined;
+ onChange: (value: string | undefined) => void;
+ minDate?: string;
+}) {
+ const { t } = useTranslation();
+
+ return (
+ <div className="flex items-center gap-x-2">
+ <input
+ type="datetime-local"
+ className="h-9 w-64 rounded-xs border border-control-border bg-transparent px-3 text-sm text-main focus:outline-none focus:ring-2 focus:ring-accent focus:border-accent"
+ value={value ?? ""}
+ min={minDate}
+ onChange={(e) => onChange(e.target.value || undefined)}
+ />
+ {value && (
+ <button
+ type="button"
+ className="p-1 rounded-full hover:bg-gray-200 text-control-placeholder shrink-0"
+ onClick={() => onChange(undefined)}
+ title={t("common.clear")}
+ >
+ <X className="h-3.5 w-3.5" />
+ </button>
+ )}
+ </div>
+ );
+}
diff --git a/frontend/src/react/locales/en-US.json b/frontend/src/react/locales/en-US.json
index 666ef92d7c..036eda1011 100644
--- a/frontend/src/react/locales/en-US.json
+++ b/frontend/src/react/locales/en-US.json
@@ -199,7 +199,13 @@
"issues": "Issues",
"manage": "Manage",
"setting": "Setting",
- "webhooks": "Webhooks"
+ "webhooks": "Webhooks",
+ "revoke": "Revoke",
+ "n-more": "+{{n}} more",
+ "scope": "Scope",
+ "classification-level": "Classification Level",
+ "columns": "Columns",
+ "resources": "Resources"
},
"create-db": {
"cluster": "Cluster",
@@ -274,6 +280,7 @@
"self": "Custom Approval"
},
"database": {
+ "all": "All databases",
"change-database": "Change Database",
"classification": {
"description": "Define classification levels to apply consistent masking policies across columns and databases."
@@ -411,7 +418,13 @@
"advanced-search": {
"filter": "Filter"
},
- "labels": "Issue Labels"
+ "labels": "Issue Labels",
+ "role-grant": {
+ "all-databases": "All",
+ "all-databases-tip": "All current and future databases in this project.",
+ "manually-select": "Manually select",
+ "use-cel": "Use CEL Expression"
+ }
},
"label": {
"error": {
@@ -585,7 +598,17 @@
"webhook-url": "Webhook URL"
},
"masking-exemption": {
- "self": "Masking Exemptions"
+ "self": "Masking Exemptions",
+ "grant-exemption": "Grant Exemption",
+ "revoke-exemption-title": "Remove masking exemption for {{member}}?",
+ "no-reason": "No reason provided",
+ "no-exemptions": "No masking exemptions granted yet",
+ "expires-today": "Expires today",
+ "expires-in-days_one": "Expires in {{days}} day",
+ "expires-in-days_other": "Expires in {{days}} days",
+ "all-levels": "All levels",
+ "n-exemptions_one": "{{n}} exemption",
+ "n-exemptions_other": "{{n}} exemptions"
}
},
"quick-action": {
@@ -909,6 +932,7 @@
"search-member": "Search member",
"select-account_one": "Select account",
"select-account_other": "Select accounts",
+ "select-account-hint": "You can search for users and groups, or input the entire email to select the service account or workload identity.",
"select-role_one": "Select role",
"select-role_other": "Select roles",
"service-account": "Service Account",
@@ -962,6 +986,7 @@
"subscription": "(Upgrade to enable role management)"
},
"sensitive-data": {
+ "never-expires": "Never expires",
"algorithms": {
"add": "Add algorithm",
"edit": "Edit algorithm",
diff --git a/frontend/src/react/locales/es-ES.json b/frontend/src/react/locales/es-ES.json
index 6142c14686..de7b8807cb 100644
--- a/frontend/src/react/locales/es-ES.json
+++ b/frontend/src/react/locales/es-ES.json
@@ -199,7 +199,13 @@
"issues": "Incidencias",
"manage": "Administrar",
"setting": "Configuración",
- "webhooks": "Webhooks"
+ "webhooks": "Webhooks",
+ "revoke": "Revocar",
+ "n-more": "+{{n}} más",
+ "scope": "Alcance",
+ "classification-level": "Nivel de clasificación",
+ "columns": "Columnas",
+ "resources": "Recursos"
},
"create-db": {
"cluster": "Clúster",
@@ -274,6 +280,7 @@
"self": "Aprobación personalizada"
},
"database": {
+ "all": "Todas las bases de datos",
"change-database": "Modificar base de datos",
"classification": {
"description": "Define classification levels to apply consistent masking policies across columns and databases."
@@ -411,7 +418,13 @@
"advanced-search": {
"filter": "Filtrar"
},
- "labels": "Etiquetas de problema"
+ "labels": "Etiquetas de problema",
+ "role-grant": {
+ "all-databases": "todas las bases de datos",
+ "all-databases-tip": "Todas las bases de datos actuales y futuras de este proyecto.",
+ "manually-select": "selección manual",
+ "use-cel": "Usar expresión CEL"
+ }
},
"label": {
"error": {
@@ -585,7 +598,17 @@
"webhook-url": "URL del webhook"
},
"masking-exemption": {
- "self": "Exenciones de Enmascaramiento"
+ "self": "Exenciones de Enmascaramiento",
+ "grant-exemption": "Conceder Exención",
+ "revoke-exemption-title": "¿Eliminar la exención de enmascaramiento para {{member}}?",
+ "no-reason": "No se proporcionó motivo",
+ "no-exemptions": "Aún no se han concedido exenciones de enmascaramiento",
+ "expires-today": "Expira hoy",
+ "expires-in-days_one": "Expira en {{days}} día",
+ "expires-in-days_other": "Expira en {{days}} días",
+ "all-levels": "Todos los niveles",
+ "n-exemptions_one": "{{n}} exención",
+ "n-exemptions_other": "{{n}} exenciones"
}
},
"quick-action": {
@@ -909,6 +932,7 @@
"search-member": "Buscar miembro",
"select-account_one": "Seleccionar cuenta",
"select-account_other": "Seleccionar cuentas",
+ "select-account-hint": "Puede buscar usuarios y grupos, o introducir el correo electrónico completo para seleccionar la cuenta de servicio o identidad de carga de trabajo.",
"select-role_one": "Seleccionar rol",
"select-role_other": "Seleccionar roles",
"service-account": "Cuenta de Servicio",
@@ -962,6 +986,7 @@
"subscription": "(Actualice para habilitar la gestión de roles)"
},
"sensitive-data": {
+ "never-expires": "Nunca expira",
"algorithms": {
"add": "Agregar algoritmo",
"edit": "Editar algoritmo",
diff --git a/frontend/src/react/locales/ja-JP.json b/frontend/src/react/locales/ja-JP.json
index c736d23075..ae5f35f1a1 100644
--- a/frontend/src/react/locales/ja-JP.json
+++ b/frontend/src/react/locales/ja-JP.json
@@ -199,7 +199,13 @@
"issues": "イシュー",
"manage": "管理",
"setting": "設定",
- "webhooks": "Webhook"
+ "webhooks": "Webhook",
+ "revoke": "キャンセル",
+ "n-more": "+{{n}} もっと",
+ "scope": "スコープ",
+ "classification-level": "分類レベル",
+ "columns": "カラム",
+ "resources": "リソース"
},
"create-db": {
"cluster": "集まる",
@@ -274,6 +280,7 @@
"self": "カスタム承認"
},
"database": {
+ "all": "すべてのデータベース",
"change-database": "データベースの変更",
"classification": {
"description": "Define classification levels to apply consistent masking policies across columns and databases."
@@ -411,7 +418,13 @@
"advanced-search": {
"filter": "フィルター"
},
- "labels": "イシューラベル"
+ "labels": "イシューラベル",
+ "role-grant": {
+ "all-databases": "すべてのデータベース",
+ "all-databases-tip": "このプロジェクトに属する現在および将来のすべてのデータベース。",
+ "manually-select": "手動選択",
+ "use-cel": "CEL式を使用"
+ }
},
"label": {
"error": {
@@ -585,7 +598,17 @@
"webhook-url": "Webhook URL"
},
"masking-exemption": {
- "self": "マスキング免除"
+ "self": "マスキング免除",
+ "grant-exemption": "免除を付与",
+ "revoke-exemption-title": "{{member}} のマスキング免除を削除しますか?",
+ "no-reason": "理由が提供されていません",
+ "no-exemptions": "マスキング免除はまだ付与されていません",
+ "expires-today": "本日期限切れ",
+ "expires-in-days_one": "{{days}} 日後に期限切れ",
+ "expires-in-days_other": "{{days}} 日後に期限切れ",
+ "all-levels": "全レベル",
+ "n-exemptions_one": "{{n}} 件の免除",
+ "n-exemptions_other": "{{n}} 件の免除"
}
},
"quick-action": {
@@ -909,6 +932,7 @@
"search-member": "メンバーを検索",
"select-account_one": "アカウントを選択",
"select-account_other": "アカウントを選択",
+ "select-account-hint": "ユーザーやグループを検索するか、完全なメールアドレスを入力してサービスアカウントまたはワークロードアイデンティティを選択できます。",
"select-role_one": "ロールを選択",
"select-role_other": "ロールを選択",
"service-account": "サービスアカウント",
@@ -962,6 +986,7 @@
"subscription": "(有料プランにアップグレードするとキャラクター管理が可能になります)"
},
"sensitive-data": {
+ "never-expires": "有効期限なし",
"algorithms": {
"add": "アルゴリズムを追加",
"edit": "アルゴリズムを編集",
diff --git a/frontend/src/react/locales/vi-VN.json b/frontend/src/react/locales/vi-VN.json
index 45b82b087f..1f34ec9aa7 100644
--- a/frontend/src/react/locales/vi-VN.json
+++ b/frontend/src/react/locales/vi-VN.json
@@ -199,7 +199,13 @@
"issues": "Vấn đề",
"manage": "Quản lý",
"setting": "Cài đặt",
- "webhooks": "Webhooks"
+ "webhooks": "Webhooks",
+ "revoke": "Thu hồi",
+ "n-more": "+{{n}} nữa",
+ "scope": "Phạm vi",
+ "classification-level": "Cấp phân loại",
+ "columns": "Cột",
+ "resources": "Tài nguyên"
},
"create-db": {
"cluster": "Cụm",
@@ -274,6 +280,7 @@
"self": "Phê duyệt tùy chỉnh"
},
"database": {
+ "all": "Tất cả cơ sở dữ liệu",
"change-database": "Thay đổi cơ sở dữ liệu",
"classification": {
"description": "Define classification levels to apply consistent masking policies across columns and databases."
@@ -411,7 +418,13 @@
"advanced-search": {
"filter": "Bộ lọc"
},
- "labels": "Nhãn vấn đề"
+ "labels": "Nhãn vấn đề",
+ "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.",
+ "manually-select": "Chọn thủ công",
+ "use-cel": "Sử dụng biểu thức CEL"
+ }
},
"label": {
"error": {
@@ -585,7 +598,17 @@
"webhook-url": "URL Webhook"
},
"masking-exemption": {
- "self": "Miễn trừ Che giấu"
+ "self": "Miễn trừ Che giấu",
+ "grant-exemption": "Cấp Miễn trừ",
+ "revoke-exemption-title": "Xóa miễn trừ che giấu cho {{member}}?",
+ "no-reason": "Không có lý do được cung cấp",
+ "no-exemptions": "Chưa có miễn trừ che giấu nào được cấp",
+ "expires-today": "Hết hạn hôm nay",
+ "expires-in-days_one": "Hết hạn sau {{days}} ngày",
+ "expires-in-days_other": "Hết hạn sau {{days}} ngày",
+ "all-levels": "Tất cả các cấp",
+ "n-exemptions_one": "{{n}} miễn trừ",
+ "n-exemptions_other": "{{n}} miễn trừ"
}
},
"quick-action": {
@@ -909,6 +932,7 @@
"search-member": "Tìm kiếm thành viên",
"select-account_one": "Chọn tài khoản",
"select-account_other": "Chọn tài khoản",
+ "select-account-hint": "Bạn có thể tìm kiếm người dùng và nhóm, hoặc nhập toàn bộ email để chọn tài khoản dịch vụ hoặc danh tính khối lượng công việc.",
"select-role_one": "Chọn vai trò",
"select-role_other": "Chọn vai trò",
"service-account": "Tài khoản dịch vụ",
@@ -962,6 +986,7 @@
"subscription": "(Nâng cấp để kích hoạt quản lý vai trò)"
},
"sensitive-data": {
+ "never-expires": "Không bao giờ hết hạn",
"algorithms": {
"add": "Thêm thuật toán",
"edit": "Chỉnh sửa thuật toán",
diff --git a/frontend/src/react/locales/zh-CN.json b/frontend/src/react/locales/zh-CN.json
index dc0e03e3c4..e7a9867afb 100644
--- a/frontend/src/react/locales/zh-CN.json
+++ b/frontend/src/react/locales/zh-CN.json
@@ -199,7 +199,13 @@
"issues": "工单",
"manage": "管理",
"setting": "设置",
- "webhooks": "Webhook"
+ "webhooks": "Webhook",
+ "revoke": "撤销",
+ "n-more": "+{{n}} 更多",
+ "scope": "范围",
+ "classification-level": "分类等级",
+ "columns": "列",
+ "resources": "资源"
},
"create-db": {
"cluster": "集群",
@@ -274,6 +280,7 @@
"self": "自定义审批"
},
"database": {
+ "all": "所有数据库",
"change-database": "变更数据库",
"classification": {
"description": "定义分类分级,跨列和数据库统一应用脱敏策略。"
@@ -411,7 +418,13 @@
"advanced-search": {
"filter": "过滤"
},
- "labels": "工单标签"
+ "labels": "工单标签",
+ "role-grant": {
+ "all-databases": "所有数据库",
+ "all-databases-tip": "所有当前和未来属于这个项目的数据库。",
+ "manually-select": "手动选择",
+ "use-cel": "使用 CEL 表达式"
+ }
},
"label": {
"error": {
@@ -585,7 +598,17 @@
"webhook-url": "Webhook URL"
},
"masking-exemption": {
- "self": "脱敏豁免"
+ "self": "脱敏豁免",
+ "grant-exemption": "授予豁免",
+ "revoke-exemption-title": "是否撤销 {{member}} 的脱敏豁免?",
+ "no-reason": "未提供原因",
+ "no-exemptions": "尚未授予脱敏豁免",
+ "expires-today": "今天到期",
+ "expires-in-days_one": "{{days}} 天后到期",
+ "expires-in-days_other": "{{days}} 天后到期",
+ "all-levels": "所有等级",
+ "n-exemptions_one": "{{n}} 项豁免",
+ "n-exemptions_other": "{{n}} 项豁免"
}
},
"quick-action": {
@@ -909,6 +932,7 @@
"search-member": "搜索成员",
"select-account_one": "选择账户",
"select-account_other": "选择账户",
+ "select-account-hint": "您可以搜索用户和组,或输入完整的电子邮件地址来选择服务账号或工作负载身份。",
"select-role_one": "选择角色",
"select-role_other": "选择角色",
"service-account": "服务账号",
@@ -962,6 +986,7 @@
"subscription": "(升级到付费方案来解锁角色管理)"
},
"sensitive-data": {
+ "never-expires": "无过期时间",
"algorithms": {
"add": "添加算法",
"edit": "编辑算法",
diff --git a/frontend/src/react/pages/project/ProjectMaskingExemptionCreatePage.tsx b/frontend/src/react/pages/project/ProjectMaskingExemptionCreatePage.tsx
new file mode 100644
index 0000000000..5562b213cc
--- /dev/null
+++ b/frontend/src/react/pages/project/ProjectMaskingExemptionCreatePage.tsx
@@ -0,0 +1,463 @@
+import { create } from "@bufbuild/protobuf";
+import dayjs from "dayjs";
+import { CircleHelp } from "lucide-react";
+import { useCallback, useEffect, useMemo, 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 { getExpressionsForDatabaseResource } from "@/components/SensitiveData/utils";
+import type { ConditionGroupExpr, Factor, Operator } from "@/plugins/cel";
+import {
+ buildCELExpr,
+ emptySimpleExpr,
+ validateSimpleExpr,
+ wrapAsGroup,
+} from "@/plugins/cel";
+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 { AccountMultiSelect } from "@/react/pages/settings/shared/AccountMultiSelect";
+import { router } from "@/router";
+import {
+ hasFeature,
+ pushNotification,
+ usePolicyV1Store,
+ useProjectV1Store,
+ useSettingV1Store,
+} from "@/store";
+import { projectNamePrefix } from "@/store/modules/v1/common";
+import type { DatabaseResource } from "@/types";
+import { ExprSchema } from "@/types/proto-es/google/type/expr_pb";
+import {
+ MaskingExemptionPolicy_ExemptionSchema,
+ MaskingExemptionPolicySchema,
+ PolicyResourceType,
+ PolicyType,
+} from "@/types/proto-es/v1/org_policy_service_pb";
+import { Setting_SettingName } from "@/types/proto-es/v1/setting_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";
+
+type RadioValue = "ALL" | "EXPRESSION" | "SELECT";
+
+export function ProjectMaskingExemptionCreatePage({
+ projectId,
+}: {
+ projectId: string;
+}) {
+ const { t } = useTranslation();
+ const projectStore = useProjectV1Store();
+ const policyStore = usePolicyV1Store();
+ const settingStore = useSettingV1Store();
+
+ const projectName = `${projectNamePrefix}${projectId}`;
+ const project = useVueState(() => projectStore.getProjectByName(projectName));
+
+ // Ensure classification config is loaded
+ useEffect(() => {
+ settingStore.getOrFetchSettingByName(
+ Setting_SettingName.DATA_CLASSIFICATION,
+ true
+ );
+ }, [settingStore]);
+
+ const hasRequiredFeature = useVueState(() =>
+ hasFeature(PlanFeature.FEATURE_DATA_MASKING)
+ );
+
+ // Form state
+ 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 [showFeatureModal, setShowFeatureModal] = useState(false);
+
+ // Validation
+ 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]
+ );
+
+ // ExprEditor config
+ 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 onRadioChange = useCallback(
+ (value: RadioValue) => {
+ if (!hasRequiredFeature && value !== "ALL") {
+ setShowFeatureModal(true);
+ return;
+ }
+ setRadioValue(value);
+ },
+ [hasRequiredFeature]
+ );
+
+ const onDismiss = useCallback(() => {
+ router.back();
+ }, []);
+
+ 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") {
+ // Build CEL expression directly
+ 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 {
+ // ALL or SELECT mode
+ const resources =
+ radioValue === "SELECT" ? databaseResources : undefined;
+
+ const resourceExpressions = (
+ resources?.map(getExpressionsForDatabaseResource) ?? [[""]]
+ ).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"),
+ });
+ onDismiss();
+ } catch (error) {
+ pushNotification({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: `${error}`,
+ });
+ } finally {
+ setProcessing(false);
+ }
+ }, [
+ processing,
+ expirationTimestamp,
+ radioValue,
+ expr,
+ databaseResources,
+ memberList,
+ description,
+ projectName,
+ policyStore,
+ t,
+ onDismiss,
+ ]);
+
+ // Min datetime for expiration picker (today start of day)
+ const minDatetime = useMemo(() => {
+ return dayjs().startOf("day").format("YYYY-MM-DDTHH:mm");
+ }, []);
+
+ return (
+ <div className="h-full flex flex-col">
+ {/* Header */}
+ <div className="px-4 pt-4">
+ <h2 className="text-lg font-medium">
+ {t("project.masking-exemption.grant-exemption")}
+ </h2>
+ <div className="border-b border-gray-200 mt-3" />
+ </div>
+
+ {/* Body */}
+ <div className="flex-1 mb-6 px-4 overflow-y-auto">
+ <div className="flex flex-col gap-y-8 pt-4">
+ <FeatureAttention feature={PlanFeature.FEATURE_DATA_MASKING} />
+
+ {/* Resources */}
+ <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-red-500">*</span>
+ </div>
+
+ {/* Radio group */}
+ <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")}
+ 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={!project}
+ className="accent-accent"
+ />
+ <div className="flex items-center gap-x-1">
+ <FeatureBadge feature={PlanFeature.FEATURE_DATA_MASKING} />
+ <span>{t("issue.role-grant.use-cel")}</span>
+ </div>
+ </label>
+
+ <label className="flex items-center gap-x-2 cursor-pointer">
+ <input
+ type="radio"
+ name="resource-mode"
+ checked={radioValue === "SELECT"}
+ onChange={() => onRadioChange("SELECT")}
+ disabled={!project}
+ className="accent-accent"
+ />
+ <div className="flex items-center gap-x-1">
+ <FeatureBadge feature={PlanFeature.FEATURE_DATA_MASKING} />
+ <span>{t("issue.role-grant.manually-select")}</span>
+ </div>
+ </label>
+ </div>
+ </div>
+
+ {/* Resource selector content */}
+ {radioValue === "SELECT" && (
+ <DatabaseResourceSelector
+ projectName={projectName}
+ value={databaseResources}
+ onChange={setDatabaseResources}
+ />
+ )}
+ {radioValue === "EXPRESSION" && (
+ <ExprEditor
+ expr={expr}
+ factorList={factorList}
+ optionConfigMap={factorOptionConfigMap}
+ factorOperatorOverrideMap={factorOperatorOverrideMap}
+ onUpdate={setExpr}
+ />
+ )}
+ </div>
+
+ {/* Reason */}
+ <div className="w-full">
+ <p className="mb-2 text-main">{t("common.reason")}</p>
+ <Input
+ value={description}
+ onChange={(e) => setDescription(e.target.value)}
+ placeholder={t("common.description")}
+ />
+ </div>
+
+ {/* Expiration */}
+ <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>
+
+ {/* Members */}
+ <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-red-500">*</span>
+ <Tooltip content={t("settings.members.select-account-hint")}>
+ <CircleHelp className="w-4 h-4 textinfolabel" />
+ </Tooltip>
+ </div>
+ <AccountMultiSelect value={memberList} onChange={setMemberList} />
+ </div>
+ </div>
+ </div>
+
+ {/* Footer */}
+ <div className="sticky bottom-0 z-10 border-t bg-white">
+ <div className="flex justify-end items-center px-4 py-3">
+ <div className="flex items-center gap-x-2">
+ <Button variant="outline" onClick={onDismiss}>
+ {t("common.cancel")}
+ </Button>
+ <Button disabled={submitDisabled || processing} onClick={onSubmit}>
+ {t("common.confirm")}
+ </Button>
+ </div>
+ </div>
+ </div>
+
+ {/* Feature modal */}
+ <Dialog
+ open={showFeatureModal}
+ onOpenChange={(open) => {
+ if (!open) setShowFeatureModal(false);
+ }}
+ >
+ <DialogContent className="p-6">
+ <DialogTitle>{t("common.warning")}</DialogTitle>
+ <FeatureAttention feature={PlanFeature.FEATURE_DATA_MASKING} />
+ <div className="flex justify-end gap-x-2 mt-4">
+ <Button
+ variant="outline"
+ onClick={() => setShowFeatureModal(false)}
+ >
+ {t("common.cancel")}
+ </Button>
+ </div>
+ </DialogContent>
+ </Dialog>
+ </div>
+ );
+}
diff --git a/frontend/src/react/pages/project/ProjectMaskingExemptionPage.tsx b/frontend/src/react/pages/project/ProjectMaskingExemptionPage.tsx
new file mode 100644
index 0000000000..6b2d998505
--- /dev/null
+++ b/frontend/src/react/pages/project/ProjectMaskingExemptionPage.tsx
@@ -0,0 +1,1472 @@
+import { create } from "@bufbuild/protobuf";
+import dayjs from "dayjs";
+import { ChevronRight, ShieldCheck } from "lucide-react";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { useTranslation } from "react-i18next";
+import {
+ buildMemberSummary,
+ generateGrantTitle,
+ getConditionExpression,
+ groupByMember,
+ parseExpirationTimestamp,
+} from "@/components/SensitiveData/exemptionDataUtils";
+import type {
+ AccessUser,
+ ClassificationLevel,
+ ExemptionGrant,
+ ExemptionMember,
+} from "@/components/SensitiveData/types";
+import { operatorDisplayLabel } from "@/plugins/cel/types/operator";
+import {
+ AdvancedSearch,
+ getValueFromScopes,
+ type ScopeOption,
+ type SearchParams,
+ type ValueOption,
+} from "@/react/components/AdvancedSearch";
+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 { Tooltip } from "@/react/components/ui/tooltip";
+import { useVueState } from "@/react/hooks/useVueState";
+import { cn } from "@/react/lib/utils";
+import { router } from "@/router";
+import { PROJECT_V1_ROUTE_MASKING_EXEMPTION_CREATE } from "@/router/dashboard/projectV1";
+import {
+ composePolicyBindings,
+ extractUserEmail,
+ hasFeature,
+ pushNotification,
+ useCurrentUserV1,
+ useDatabaseV1Store,
+ useGroupStore,
+ usePolicyV1Store,
+ useProjectV1Store,
+ useSettingV1Store,
+ useUserStore,
+} from "@/store";
+import { projectNamePrefix } from "@/store/modules/v1/common";
+import type { DatabaseResource } from "@/types";
+import {
+ groupBindingPrefix,
+ serviceAccountBindingPrefix,
+ workloadIdentityBindingPrefix,
+} from "@/types";
+import { ExprSchema } from "@/types/proto-es/google/type/expr_pb";
+import type { MaskingExemptionPolicy_Exemption } from "@/types/proto-es/v1/org_policy_service_pb";
+import {
+ MaskingExemptionPolicySchema,
+ PolicyType,
+} from "@/types/proto-es/v1/org_policy_service_pb";
+import { Setting_SettingName } from "@/types/proto-es/v1/setting_service_pb";
+import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";
+import { hasProjectPermissionV2 } from "@/utils";
+import {
+ batchConvertFromCELString,
+ type ConditionExpression,
+} from "@/utils/issue/cel";
+import { extractDatabaseResourceName } from "@/utils/v1/database";
+
+// ============================================================
+// Helpers
+// ============================================================
+
+const isGrantActive = (g: ExemptionGrant): boolean =>
+ !g.expirationTimestamp || g.expirationTimestamp > Date.now();
+
+// ============================================================
+// ProjectMaskingExemptionPage
+// ============================================================
+
+export function ProjectMaskingExemptionPage({
+ projectId,
+}: {
+ projectId: string;
+}) {
+ const { t } = useTranslation();
+ const projectStore = useProjectV1Store();
+ const databaseStore = useDatabaseV1Store();
+ const userStore = useUserStore();
+ const currentUser = useVueState(() => useCurrentUserV1().value);
+
+ const projectName = `${projectNamePrefix}${projectId}`;
+ const project = useVueState(() => projectStore.getProjectByName(projectName));
+ const showDatabaseLink = useMemo(
+ () =>
+ project ? hasProjectPermissionV2(project, "bb.databases.get") : false,
+ [project]
+ );
+ const hasPermission = useMemo(
+ () =>
+ project
+ ? hasProjectPermissionV2(
+ project,
+ "bb.policies.updateMaskingExemptionPolicy"
+ )
+ : false,
+ [project]
+ );
+ const hasSensitiveDataFeature = useVueState(() =>
+ hasFeature(PlanFeature.FEATURE_DATA_MASKING)
+ );
+
+ const membersFromVue = useExemptionDataReact(projectName);
+
+ const [searchParams, setSearchParams] = useState<SearchParams>({
+ query: "",
+ scopes: [{ id: "status", value: "active" }],
+ });
+
+ const [selectedMemberKey, setSelectedMemberKey] = useState("");
+ const [showFeatureModal, setShowFeatureModal] = useState(false);
+ const [revokeConfirm, setRevokeConfirm] = useState<{
+ member: ExemptionMember;
+ grant: ExemptionGrant;
+ } | null>(null);
+
+ // Wide screen detection (1024px breakpoint)
+ const [isWide, setIsWide] = useState(
+ () => typeof window !== "undefined" && window.innerWidth >= 1024
+ );
+ useEffect(() => {
+ const handler = () => setIsWide(window.innerWidth >= 1024);
+ window.addEventListener("resize", handler);
+ return () => window.removeEventListener("resize", handler);
+ }, []);
+
+ const activeDatabaseFilter = useMemo(
+ () => getValueFromScopes(searchParams, "database") || undefined,
+ [searchParams]
+ );
+
+ const withFilteredGrants = useCallback(
+ (m: ExemptionMember, grants: ExemptionGrant[]): ExemptionMember => ({
+ ...m,
+ grants,
+ ...buildMemberSummary(grants),
+ }),
+ []
+ );
+
+ const filteredMembers = useMemo(() => {
+ let result = membersFromVue.members;
+
+ // Free-text query
+ const query = searchParams.query.trim().toLowerCase();
+ if (query) {
+ result = result.filter((m) => m.member.toLowerCase().includes(query));
+ }
+
+ const userScope = getValueFromScopes(searchParams, "user");
+ if (userScope) {
+ result = result.filter((m) =>
+ m.member.toLowerCase().includes(userScope.toLowerCase())
+ );
+ }
+
+ // Status filter
+ const statusScope = getValueFromScopes(searchParams, "status");
+ if (statusScope === "active") {
+ result = result
+ .map((m) => withFilteredGrants(m, m.grants.filter(isGrantActive)))
+ .filter((m) => m.grants.length > 0);
+ } else if (statusScope === "expired") {
+ result = result
+ .map((m) =>
+ withFilteredGrants(
+ m,
+ m.grants.filter((g) => !isGrantActive(g))
+ )
+ )
+ .filter((m) => m.grants.length > 0);
+ }
+
+ // Database filter
+ const dbScope = activeDatabaseFilter;
+ if (dbScope) {
+ const matchesDb = (g: ExemptionGrant) =>
+ !g.databaseResources ||
+ g.databaseResources.length === 0 ||
+ g.databaseResources.some((r) => r.databaseFullName === dbScope);
+ result = result
+ .map((m) => withFilteredGrants(m, m.grants.filter(matchesDb)))
+ .filter((m) => m.grants.length > 0);
+ }
+
+ return result;
+ }, [
+ membersFromVue.members,
+ searchParams,
+ activeDatabaseFilter,
+ withFilteredGrants,
+ ]);
+
+ const selectedMemberData = useMemo(
+ () => filteredMembers.find((m) => m.member === selectedMemberKey),
+ [filteredMembers, selectedMemberKey]
+ );
+
+ // Auto-select first member in wide mode
+ useEffect(() => {
+ if (isWide && filteredMembers.length > 0) {
+ if (
+ !selectedMemberKey ||
+ !filteredMembers.some((m) => m.member === selectedMemberKey)
+ ) {
+ setSelectedMemberKey(filteredMembers[0].member);
+ }
+ }
+ }, [isWide, filteredMembers, selectedMemberKey]);
+
+ const handleGrantClick = useCallback(() => {
+ if (!hasSensitiveDataFeature) {
+ setShowFeatureModal(true);
+ return;
+ }
+ router.push({ name: PROJECT_V1_ROUTE_MASKING_EXEMPTION_CREATE });
+ }, [hasSensitiveDataFeature]);
+
+ const stripMemberPrefix = (raw: string): string => {
+ const idx = raw.indexOf(":");
+ return idx >= 0 ? raw.substring(idx + 1) : raw;
+ };
+
+ const handleRevoke = useCallback(
+ (member: ExemptionMember, grant: ExemptionGrant) => {
+ setRevokeConfirm({ member, grant });
+ },
+ []
+ );
+
+ const confirmRevoke = useCallback(async () => {
+ if (!revokeConfirm) return;
+ await membersFromVue.revokeGrant(revokeConfirm.member, revokeConfirm.grant);
+ setRevokeConfirm(null);
+ }, [revokeConfirm, membersFromVue]);
+
+ // Scope options for advanced search
+ const searchDatabases = useCallback(
+ async (keyword: string): Promise<ValueOption[]> => {
+ const result = await databaseStore.fetchDatabases({
+ parent: projectName,
+ pageSize: 50,
+ filter: keyword ? { query: keyword } : undefined,
+ });
+ return result.databases.map((db) => {
+ const { database: dbName } = extractDatabaseResourceName(db.name);
+ return {
+ value: db.name,
+ keywords: [dbName, db.name],
+ custom: true,
+ render: () => (
+ <span className="inline-flex items-center gap-x-1">
+ <span>{dbName}</span>
+ </span>
+ ),
+ };
+ });
+ },
+ [databaseStore, projectName]
+ );
+
+ const searchUsers = useCallback(
+ async (keyword: string): Promise<ValueOption[]> => {
+ const result = await userStore.fetchUserList({
+ pageSize: 50,
+ filter: keyword ? { query: keyword } : undefined,
+ });
+ return result.users.map((u) => ({
+ value: u.email,
+ keywords: [u.email, u.title],
+ custom: true,
+ render: () => (
+ <span className="inline-flex items-center gap-x-1.5">
+ <span
+ className="w-5 h-5 rounded-full text-white text-xs flex items-center justify-center shrink-0"
+ style={{
+ backgroundColor: `hsl(${Math.abs(hashString(u.title)) % 360}, 55%, 55%)`,
+ }}
+ >
+ {u.title.charAt(0).toUpperCase()}
+ </span>
+ <span>{u.title}</span>
+ {currentUser && u.name === currentUser.name && (
+ <span className="text-xs bg-green-100 text-green-700 rounded-full px-1.5">
+ {t("common.you")}
+ </span>
+ )}
+ <span className="text-control-light">{u.email}</span>
+ </span>
+ ),
+ }));
+ },
+ [userStore, currentUser, t]
+ );
+
+ const scopeOptions: ScopeOption[] = useMemo(
+ () => [
+ {
+ id: "database",
+ title: t("common.database"),
+ onSearch: searchDatabases,
+ },
+ {
+ id: "user",
+ title: t("common.users"),
+ onSearch: searchUsers,
+ },
+ {
+ id: "status",
+ title: t("common.status"),
+ options: [
+ {
+ value: "active",
+ keywords: ["active"],
+ render: () => <span>{t("common.active")}</span>,
+ },
+ {
+ value: "expired",
+ keywords: ["expired"],
+ render: () => <span>{t("sql-editor.expired")}</span>,
+ },
+ ],
+ },
+ ],
+ [t, searchDatabases, searchUsers]
+ );
+
+ // Preset tabs
+ const presets = useMemo(
+ () => [
+ { id: "active", label: t("common.active") },
+ { id: "expired", label: t("sql-editor.expired") },
+ { id: "all", label: t("common.all") },
+ ],
+ [t]
+ );
+
+ const activePreset = useMemo(() => {
+ const status = getValueFromScopes(searchParams, "status");
+ return status || "active";
+ }, [searchParams]);
+
+ const selectPreset = useCallback(
+ (id: string) => {
+ const newScopes = searchParams.scopes.filter((s) => s.id !== "status");
+ if (id !== "all") {
+ newScopes.push({ id: "status", value: id });
+ }
+ setSearchParams({ ...searchParams, scopes: newScopes });
+ },
+ [searchParams]
+ );
+
+ return (
+ <div className="flex flex-col">
+ <div className="px-4 py-3">
+ <div className="mb-2">
+ <FeatureAttention feature={PlanFeature.FEATURE_DATA_MASKING} />
+ </div>
+ <div className="flex flex-row items-center gap-x-2 mb-2">
+ <AdvancedSearch
+ params={searchParams}
+ onParamsChange={setSearchParams}
+ scopeOptions={scopeOptions}
+ placeholder={t("issue.advanced-search.filter")}
+ />
+ <Button onClick={handleGrantClick} disabled={!hasPermission}>
+ <ShieldCheck className="w-4 h-4" />
+ <FeatureBadge
+ feature={PlanFeature.FEATURE_DATA_MASKING}
+ className="text-white"
+ />
+ {t("project.masking-exemption.grant-exemption")}
+ </Button>
+ </div>
+
+ {/* Preset tabs */}
+ <div className="shrink-0">
+ <div className="flex border-b border-gray-200">
+ {presets.map((preset) => (
+ <button
+ key={preset.id}
+ className={cn(
+ "px-3 py-1.5 text-sm font-medium border-b-2 -mb-px transition-colors",
+ activePreset === preset.id
+ ? "border-accent text-accent"
+ : "border-transparent text-control-light hover:text-control hover:border-gray-300"
+ )}
+ onClick={() => selectPreset(preset.id)}
+ >
+ {preset.label}
+ </button>
+ ))}
+ </div>
+ </div>
+ </div>
+
+ {/* Wide view: side-by-side */}
+ {isWide ? (
+ <div className="flex" style={{ height: "calc(100vh - 11rem)" }}>
+ <ExemptionMemberList
+ className="w-[360px] shrink-0 border-r border-gray-200 overflow-y-auto"
+ members={filteredMembers}
+ disabled={!hasPermission}
+ loading={membersFromVue.loading}
+ selectedMemberKey={selectedMemberKey}
+ onSelect={setSelectedMemberKey}
+ onRevoke={handleRevoke}
+ />
+ <div className="flex-1 min-w-0 overflow-y-auto">
+ {!membersFromVue.loading && selectedMemberData ? (
+ <ExemptionDetailPanel
+ member={selectedMemberData}
+ disabled={!hasPermission}
+ showDatabaseLink={showDatabaseLink}
+ databaseFilter={activeDatabaseFilter}
+ onRevoke={(grant) => handleRevoke(selectedMemberData, grant)}
+ />
+ ) : !membersFromVue.loading ? (
+ <div className="flex items-center justify-center h-full text-control-placeholder text-sm">
+ {t("project.masking-exemption.no-exemptions")}
+ </div>
+ ) : null}
+ </div>
+ </div>
+ ) : (
+ /* Narrow view: expandable list */
+ <ExemptionMemberList
+ members={filteredMembers}
+ disabled={!hasPermission}
+ loading={membersFromVue.loading}
+ expandable
+ showDatabaseLink={showDatabaseLink}
+ databaseFilter={activeDatabaseFilter}
+ onRevoke={handleRevoke}
+ />
+ )}
+
+ {/* Feature modal — navigate to subscription page */}
+ <Dialog
+ open={showFeatureModal}
+ onOpenChange={(open) => {
+ if (!open) setShowFeatureModal(false);
+ }}
+ >
+ <DialogContent className="p-6">
+ <DialogTitle>{t("common.warning")}</DialogTitle>
+ <FeatureAttention feature={PlanFeature.FEATURE_DATA_MASKING} />
+ <div className="flex justify-end gap-x-2 mt-4">
+ <Button
+ variant="outline"
+ onClick={() => setShowFeatureModal(false)}
+ >
+ {t("common.cancel")}
+ </Button>
+ </div>
+ </DialogContent>
+ </Dialog>
+
+ {/* Revoke confirmation dialog */}
+ <Dialog
+ open={revokeConfirm !== null}
+ onOpenChange={(open) => {
+ if (!open) setRevokeConfirm(null);
+ }}
+ >
+ <DialogContent className="p-6">
+ <DialogTitle>{t("common.warning")}</DialogTitle>
+ <p className="text-sm text-control-light mt-2">
+ {revokeConfirm
+ ? t("project.masking-exemption.revoke-exemption-title", {
+ member: stripMemberPrefix(revokeConfirm.member.member),
+ })
+ : ""}
+ </p>
+ <div className="flex justify-end gap-x-2 mt-4">
+ <Button variant="outline" onClick={() => setRevokeConfirm(null)}>
+ {t("common.cancel")}
+ </Button>
+ <Button variant="destructive" onClick={confirmRevoke}>
+ {t("common.confirm")}
+ </Button>
+ </div>
+ </DialogContent>
+ </Dialog>
+ </div>
+ );
+}
+
+// ============================================================
+// useExemptionDataReact — reimplements useExemptionData for React
+// ============================================================
+
+function getAccessUsers(
+ exemption: MaskingExemptionPolicy_Exemption,
+ condition: ConditionExpression
+): AccessUser[] {
+ const expression = exemption.condition?.expression ?? "";
+ const description = exemption.condition?.description ?? "";
+ const expirationTimestamp = parseExpirationTimestamp(expression);
+ const conditionExpression = getConditionExpression(expression);
+
+ return exemption.members.map((member) => ({
+ type: member.startsWith(groupBindingPrefix)
+ ? ("group" as const)
+ : ("user" as const),
+ member,
+ expirationTimestamp,
+ rawExpression: expression,
+ description,
+ databaseResources:
+ condition.databaseResources && condition.databaseResources.length > 0
+ ? condition.databaseResources
+ : undefined,
+ conditionExpression,
+ }));
+}
+
+function rebuildExemptions(accessList: AccessUser[]) {
+ const expressionsMap = new Map<
+ string,
+ { description: string; members: string[] }
+ >();
+
+ for (const accessUser of accessList) {
+ const expressions = accessUser.rawExpression.split(" && ").filter((e) => e);
+ const index = expressions.findIndex((exp) =>
+ exp.startsWith("request.time")
+ );
+ if (index >= 0) {
+ if (!accessUser.expirationTimestamp) {
+ expressions.splice(index, 1);
+ } else {
+ expressions[index] = `request.time < timestamp("${new Date(
+ accessUser.expirationTimestamp
+ ).toISOString()}")`;
+ }
+ } else if (accessUser.expirationTimestamp) {
+ expressions.push(
+ `request.time < timestamp("${new Date(
+ accessUser.expirationTimestamp
+ ).toISOString()}")`
+ );
+ }
+ const finalExpression = expressions.join(" && ");
+ if (!expressionsMap.has(finalExpression)) {
+ expressionsMap.set(finalExpression, {
+ description: accessUser.description,
+ members: [],
+ });
+ }
+ expressionsMap.get(finalExpression)!.members.push(accessUser.member);
+ }
+
+ const exemptions = [];
+ for (const [expression, { description, members }] of expressionsMap) {
+ exemptions.push({
+ members,
+ condition: create(ExprSchema, { description, expression }),
+ });
+ }
+ return exemptions;
+}
+
+function useExemptionDataReact(projectName: string) {
+ const { t } = useTranslation();
+ const policyStore = usePolicyV1Store();
+ const settingStore = useSettingV1Store();
+
+ // Ensure group store is initialized for composePolicyBindings
+ useGroupStore();
+
+ // Ensure classification config is loaded
+ useEffect(() => {
+ settingStore.getOrFetchSettingByName(
+ Setting_SettingName.DATA_CLASSIFICATION,
+ true
+ );
+ }, [settingStore]);
+
+ const [rawAccessList, setRawAccessList] = useState<AccessUser[]>([]);
+ const [loading, setLoading] = useState(true);
+ const processingRef = useRef(false);
+ const fetchGenRef = useRef(0);
+ // Keep rawAccessList accessible to revokeGrant without stale closure
+ const rawAccessListRef = useRef(rawAccessList);
+ rawAccessListRef.current = rawAccessList;
+
+ // Fetch policy and parse exemptions
+ const fetchData = useCallback(async () => {
+ setLoading(true);
+ const generation = ++fetchGenRef.current;
+
+ try {
+ const pol = await policyStore.getOrFetchPolicyByParentAndType({
+ parentPath: projectName,
+ policyType: PolicyType.MASKING_EXEMPTION,
+ });
+
+ if (generation !== fetchGenRef.current) return;
+
+ if (!pol || pol.policy?.case !== "maskingExemptionPolicy") {
+ setRawAccessList([]);
+ setLoading(false);
+ return;
+ }
+
+ const { exemptions } = pol.policy.value;
+ const expressionList = exemptions.map((e) =>
+ e.condition?.expression ? e.condition.expression : "true"
+ );
+ const conditionList = await batchConvertFromCELString(expressionList);
+
+ if (generation !== fetchGenRef.current) return;
+
+ await composePolicyBindings(exemptions, true);
+
+ const memberMap = new Map<string, AccessUser>();
+ for (let i = 0; i < exemptions.length; i++) {
+ const exemption = exemptions[i];
+ const condition = conditionList[i];
+ const expr = exemption.condition?.expression ?? "";
+ const desc = exemption.condition?.description ?? "";
+ for (const item of getAccessUsers(exemption, condition)) {
+ const uniqueKey = `${item.member}:${expr}.${desc}:${i}`;
+ memberMap.set(uniqueKey, item);
+ }
+ }
+
+ if (generation !== fetchGenRef.current) return;
+
+ setRawAccessList([...memberMap.values()]);
+ } finally {
+ if (generation === fetchGenRef.current) {
+ setLoading(false);
+ }
+ }
+ }, [projectName, policyStore]);
+
+ useEffect(() => {
+ fetchData();
+ }, [fetchData]);
+
+ // Subscribe to policy changes in the store to re-fetch.
+ // Track the number of exemptions so we detect content changes,
+ // not just the policy case discriminator which is always the same.
+ const policyExemptionCount = useVueState(() => {
+ const pol = policyStore.getPolicyByParentAndType({
+ parentPath: projectName,
+ policyType: PolicyType.MASKING_EXEMPTION,
+ });
+ if (pol?.policy?.case === "maskingExemptionPolicy") {
+ return pol.policy.value.exemptions.length;
+ }
+ return -1;
+ });
+
+ // Re-fetch when policy changes (e.g. after revoke from another tab/action)
+ const policyCountRef = useRef(policyExemptionCount);
+ useEffect(() => {
+ // Skip initial mount — fetchData already runs from the effect above.
+ // Only re-fetch when the store's exemption count actually changes.
+ if (
+ fetchGenRef.current > 0 &&
+ policyCountRef.current !== policyExemptionCount
+ ) {
+ policyCountRef.current = policyExemptionCount;
+ fetchData();
+ }
+ }, [policyExemptionCount, fetchData]);
+
+ const members = useMemo<ExemptionMember[]>(
+ () => groupByMember(rawAccessList),
+ [rawAccessList]
+ );
+
+ const revokeGrant = useCallback(
+ async (member: ExemptionMember, grant: ExemptionGrant) => {
+ if (processingRef.current) return;
+ processingRef.current = true;
+
+ const currentList = [...rawAccessListRef.current];
+ const idx = currentList.findIndex(
+ (a) =>
+ a.member === member.member &&
+ a.rawExpression === grant.rawExpression &&
+ (a.description || "") === grant.description
+ );
+ if (idx < 0) {
+ processingRef.current = false;
+ return;
+ }
+
+ const [removed] = currentList.splice(idx, 1);
+ setRawAccessList(currentList);
+
+ try {
+ // Rebuild and save policy
+ const pol = await policyStore.getOrFetchPolicyByParentAndType({
+ parentPath: projectName,
+ policyType: PolicyType.MASKING_EXEMPTION,
+ });
+ if (pol) {
+ pol.policy = {
+ case: "maskingExemptionPolicy",
+ value: create(MaskingExemptionPolicySchema, {
+ exemptions: rebuildExemptions(currentList),
+ }),
+ };
+ await policyStore.upsertPolicy({
+ parentPath: projectName,
+ policy: pol,
+ });
+ }
+ pushNotification({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t("common.updated"),
+ });
+ } catch (error) {
+ // Restore on failure
+ const restored = [...rawAccessListRef.current];
+ restored.splice(idx, 0, removed);
+ setRawAccessList(restored);
+ pushNotification({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: `${error}`,
+ });
+ } finally {
+ processingRef.current = false;
+ }
+ },
+ [projectName, policyStore, t]
+ );
+
+ return { members, loading, revokeGrant };
+}
+
+// ============================================================
+// ExemptionMemberList
+// ============================================================
+
+function ExemptionMemberList({
+ className,
+ members,
+ disabled,
+ loading = false,
+ expandable = false,
+ showDatabaseLink = true,
+ databaseFilter,
+ selectedMemberKey,
+ onSelect,
+ onRevoke,
+}: {
+ className?: string;
+ members: ExemptionMember[];
+ disabled: boolean;
+ loading?: boolean;
+ expandable?: boolean;
+ showDatabaseLink?: boolean;
+ databaseFilter?: string;
+ selectedMemberKey?: string;
+ onSelect?: (key: string) => void;
+ onRevoke: (member: ExemptionMember, grant: ExemptionGrant) => void;
+}) {
+ const { t } = useTranslation();
+ const [expandedMemberKey, setExpandedMemberKey] = useState("");
+
+ if (loading) {
+ return (
+ <div className={cn("overflow-y-auto", className)}>
+ <div className="flex items-center justify-center py-12">
+ <div className="animate-spin rounded-full h-5 w-5 border-2 border-accent border-t-transparent" />
+ </div>
+ </div>
+ );
+ }
+
+ if (members.length === 0) {
+ return (
+ <div className={cn("overflow-y-auto", className)}>
+ <div className="flex items-center justify-center py-12 text-control-placeholder text-sm">
+ {t("project.masking-exemption.no-exemptions")}
+ </div>
+ </div>
+ );
+ }
+
+ return (
+ <div className={cn("overflow-y-auto", className)}>
+ <div className="divide-y divide-gray-100">
+ {members.map((member) => (
+ <div key={member.member}>
+ <ExemptionMemberItem
+ member={member}
+ selected={!expandable && selectedMemberKey === member.member}
+ expandable={expandable}
+ expanded={expandable && expandedMemberKey === member.member}
+ onSelect={() => onSelect?.(member.member)}
+ onToggle={() =>
+ setExpandedMemberKey(
+ expandedMemberKey === member.member ? "" : member.member
+ )
+ }
+ />
+ {/* Inline detail panel in narrow/expandable mode */}
+ {expandable && expandedMemberKey === member.member && (
+ <div className="border-t border-b border-gray-200">
+ <ExemptionDetailPanel
+ member={member}
+ disabled={disabled}
+ showDatabaseLink={showDatabaseLink}
+ databaseFilter={databaseFilter}
+ onRevoke={(grant) => onRevoke(member, grant)}
+ />
+ </div>
+ )}
+ </div>
+ ))}
+ </div>
+ </div>
+ );
+}
+
+// ============================================================
+// ExemptionMemberItem
+// ============================================================
+
+function ExemptionMemberItem({
+ member,
+ selected = false,
+ expanded = false,
+ expandable = false,
+ onSelect,
+ onToggle,
+}: {
+ member: ExemptionMember;
+ selected?: boolean;
+ expanded?: boolean;
+ expandable?: boolean;
+ onSelect: () => void;
+ onToggle: () => void;
+}) {
+ const { t } = useTranslation();
+
+ const displayName = useMemo(() => {
+ const raw = member.member;
+ const idx = raw.indexOf(":");
+ return idx >= 0 ? raw.substring(idx + 1) : raw;
+ }, [member.member]);
+
+ const isServiceAccount = member.member.startsWith(
+ serviceAccountBindingPrefix
+ );
+ const isWorkloadIdentity = member.member.startsWith(
+ workloadIdentityBindingPrefix
+ );
+
+ const scopeSummary = useMemo(() => {
+ const n = member.grants.length;
+ const exemptionWord = t("project.masking-exemption.n-exemptions", {
+ n,
+ count: n,
+ });
+
+ const realDbs = member.databaseNames.filter((name) => name !== "");
+ const hasAllDbs = member.databaseNames.includes("");
+
+ const parts: string[] = [];
+ if (realDbs.length > 0) {
+ parts.push(realDbs.join(", "));
+ }
+ if (hasAllDbs) {
+ parts.push(t("database.all"));
+ }
+
+ const scope = parts.join(", ");
+ return scope ? `${exemptionWord} · ${scope}` : exemptionWord;
+ }, [member, t]);
+
+ const handleClick = () => {
+ if (expandable) {
+ onToggle();
+ } else {
+ onSelect();
+ }
+ };
+
+ // Simple avatar
+ const avatarLetter = displayName.charAt(0).toUpperCase();
+
+ return (
+ <div
+ className={cn(
+ "flex items-center gap-x-3 px-3 py-2.5 cursor-pointer rounded transition-colors",
+ selected ? "bg-blue-50" : "hover:bg-gray-50"
+ )}
+ onClick={handleClick}
+ >
+ {/* Chevron for expandable mode */}
+ {expandable && (
+ <ChevronRight
+ className={cn(
+ "w-4 h-4 shrink-0 text-control-placeholder transition-transform",
+ expanded && "rotate-90"
+ )}
+ />
+ )}
+
+ {/* Avatar */}
+ <div
+ className="w-8 h-8 rounded-full flex items-center justify-center text-white text-sm font-medium shrink-0"
+ style={{
+ backgroundColor: `hsl(${Math.abs(hashString(displayName)) % 360}, 55%, 55%)`,
+ }}
+ >
+ {avatarLetter}
+ </div>
+
+ {/* Content */}
+ <div className="flex-1 min-w-0">
+ <div className="flex items-center gap-x-1.5">
+ <span className="font-medium text-sm truncate">{displayName}</span>
+ {member.type === "group" && (
+ <span className="inline-flex items-center rounded-full px-2 py-0.5 text-xs border border-gray-300 bg-white">
+ {t("common.groups")}
+ </span>
+ )}
+ {isServiceAccount && (
+ <span className="inline-flex items-center rounded-full px-2 py-0.5 text-xs border border-blue-300 bg-blue-50 text-blue-700">
+ {t("settings.members.service-account")}
+ </span>
+ )}
+ {isWorkloadIdentity && (
+ <span className="inline-flex items-center rounded-full px-2 py-0.5 text-xs border border-blue-300 bg-blue-50 text-blue-700">
+ {t("settings.members.workload-identity")}
+ </span>
+ )}
+ </div>
+ <div className="text-xs text-control-light truncate mt-0.5">
+ {scopeSummary}
+ </div>
+ </div>
+ </div>
+ );
+}
+
+// ============================================================
+// ExemptionDetailPanel
+// ============================================================
+
+function ExemptionDetailPanel({
+ member,
+ disabled,
+ showDatabaseLink = true,
+ databaseFilter,
+ onRevoke,
+}: {
+ member: ExemptionMember;
+ disabled: boolean;
+ showDatabaseLink?: boolean;
+ databaseFilter?: string;
+ onRevoke: (grant: ExemptionGrant) => void;
+}) {
+ const { t } = useTranslation();
+ const groupStore = useGroupStore();
+
+ const userEmail = useMemo(
+ () => extractUserEmail(member.member),
+ [member.member]
+ );
+
+ const group = useVueState(() => {
+ if (!member.member.startsWith(groupBindingPrefix)) return undefined;
+ return groupStore.getGroupByIdentifier(member.member);
+ });
+
+ const grantMatchesFilter = (grant: ExemptionGrant): boolean => {
+ if (!databaseFilter) return false;
+ return (
+ grant.databaseResources?.some(
+ (r) => r.databaseFullName === databaseFilter
+ ) ?? false
+ );
+ };
+
+ const shouldExpand = (idx: number): boolean => {
+ const grant = member.grants[idx];
+ if (databaseFilter && grantMatchesFilter(grant)) {
+ return true;
+ }
+ if (member.grants.length >= 3) {
+ return idx === 0;
+ }
+ return true;
+ };
+
+ return (
+ <div className="flex flex-col">
+ {/* Header */}
+ <div className="px-4 pt-3 pb-1">
+ <div className="flex items-center gap-x-2">
+ {member.type === "group" ? (
+ <span className="font-medium">{group?.title ?? member.member}</span>
+ ) : member.member.startsWith(serviceAccountBindingPrefix) ||
+ member.member.startsWith(workloadIdentityBindingPrefix) ? (
+ <span className="font-medium">{userEmail}</span>
+ ) : (
+ <a
+ className="normal-link font-medium"
+ href={`/users/${userEmail}`}
+ onClick={(e) => {
+ e.preventDefault();
+ router.push(`/users/${userEmail}`);
+ }}
+ >
+ {userEmail}
+ </a>
+ )}
+ </div>
+ <div className="mt-1 text-sm textinfolabel">
+ {member.grants.length}{" "}
+ {t("project.masking-exemption.self").toLowerCase()}
+ </div>
+ </div>
+
+ {/* Grants as cards */}
+ <div className="flex flex-col gap-y-3 px-4 pb-4">
+ {member.grants.map((grant, idx) => (
+ <div
+ key={grant.id}
+ className="border border-gray-200 rounded-lg overflow-hidden pt-4"
+ >
+ <ExemptionGrantSection
+ grant={grant}
+ disabled={disabled}
+ showDatabaseLink={showDatabaseLink}
+ defaultExpanded={shouldExpand(idx)}
+ onRevoke={() => onRevoke(grant)}
+ />
+ </div>
+ ))}
+ </div>
+ </div>
+ );
+}
+
+// ============================================================
+// ExemptionGrantSection
+// ============================================================
+
+function ExemptionGrantSection({
+ grant,
+ disabled,
+ showDatabaseLink = true,
+ defaultExpanded = true,
+ onRevoke,
+}: {
+ grant: ExemptionGrant;
+ disabled: boolean;
+ showDatabaseLink?: boolean;
+ defaultExpanded?: boolean;
+ onRevoke: () => void;
+}) {
+ const { t } = useTranslation();
+ const [expanded, setExpanded] = useState(defaultExpanded);
+
+ const title = useMemo(() => generateGrantTitle(grant), [grant]);
+
+ const isExpired = useMemo(
+ () =>
+ !!grant.expirationTimestamp && grant.expirationTimestamp <= Date.now(),
+ [grant.expirationTimestamp]
+ );
+
+ const expiryLabel = useMemo(() => {
+ if (!grant.expirationTimestamp) return "";
+ const msRemaining = grant.expirationTimestamp - Date.now();
+ const hoursRemaining = msRemaining / (1000 * 60 * 60);
+ if (hoursRemaining < 24)
+ return t("project.masking-exemption.expires-today");
+ const days = Math.ceil(hoursRemaining / 24);
+ return t("project.masking-exemption.expires-in-days", {
+ days,
+ count: days,
+ });
+ }, [grant.expirationTimestamp, t]);
+
+ return (
+ <div>
+ {/* Header */}
+ <div
+ className="flex items-center justify-between px-4 py-2 cursor-pointer select-none"
+ onClick={() => setExpanded(!expanded)}
+ >
+ <div className="flex items-center gap-x-3">
+ <ChevronRight
+ className={cn(
+ "w-4 h-4 shrink-0 text-control-placeholder transition-transform",
+ expanded && "rotate-90"
+ )}
+ />
+ <span className="font-medium text-sm">{title}</span>
+ {grant.expirationTimestamp && isExpired ? (
+ <>
+ <span className="text-xs text-control-light line-through">
+ {dayjs(grant.expirationTimestamp).format("YYYY-MM-DD HH:mm")}
+ </span>
+ <span className="text-xs text-control-light">
+ ({t("sql-editor.expired")})
+ </span>
+ </>
+ ) : grant.expirationTimestamp ? (
+ <>
+ <span className="text-xs font-medium text-blue-600">
+ {expiryLabel}
+ </span>
+ <span className="text-xs text-control-light">
+ ({dayjs(grant.expirationTimestamp).format("YYYY-MM-DD HH:mm")})
+ </span>
+ </>
+ ) : (
+ <span className="text-xs font-medium text-amber-600">
+ {t("settings.sensitive-data.never-expires")}
+ </span>
+ )}
+ </div>
+ <Button
+ variant="ghost"
+ size="sm"
+ className="text-error"
+ disabled={disabled}
+ onClick={(e) => {
+ e.stopPropagation();
+ onRevoke();
+ }}
+ >
+ {t("common.revoke")}
+ </Button>
+ </div>
+
+ {/* Content */}
+ {expanded && (
+ <div className="px-4 pb-4">
+ {/* Reason */}
+ <div className="mb-3 text-sm border-l-2 border-gray-300 pl-3 py-1 textinfolabel">
+ <span className="font-medium text-gray-600">
+ {t("common.reason")}:
+ </span>{" "}
+ {grant.description || t("project.masking-exemption.no-reason")}
+ </div>
+
+ {grant.databaseResources && grant.databaseResources.length > 0 ? (
+ <ExemptionResourceTable
+ databaseResources={grant.databaseResources}
+ classificationLevel={grant.classificationLevel}
+ showDatabaseLink={showDatabaseLink}
+ />
+ ) : (
+ <ExemptionLevelCard
+ classificationLevel={grant.classificationLevel}
+ />
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
+
+// ============================================================
+// ExemptionResourceTable
+// ============================================================
+
+const COLUMN_VISIBLE_LIMIT = 3;
+
+function ExemptionResourceTable({
+ databaseResources,
+ classificationLevel,
+ showDatabaseLink = true,
+}: {
+ databaseResources: DatabaseResource[];
+ classificationLevel?: ClassificationLevel;
+ showDatabaseLink?: boolean;
+}) {
+ const { t } = useTranslation();
+
+ const isSentinel = (value: string): boolean => value === "";
+
+ const displayInstance = (resource: DatabaseResource): string => {
+ const { instanceName } = extractDatabaseResourceName(
+ resource.databaseFullName
+ );
+ return isSentinel(instanceName) ? t("database.all") : instanceName;
+ };
+
+ const handleDatabaseClick = (resource: DatabaseResource) => {
+ const path = resource.databaseFullName.startsWith("/")
+ ? resource.databaseFullName
+ : `/${resource.databaseFullName}`;
+ router.push(path);
+ };
+
+ return (
+ <div className="overflow-x-auto">
+ <table className="w-full text-sm table-fixed min-w-[600px]">
+ <colgroup>
+ <col style={{ width: "16%" }} />
+ <col style={{ width: "16%" }} />
+ <col style={{ width: "14%" }} />
+ <col style={{ width: "18%" }} />
+ <col style={{ width: "20%" }} />
+ <col style={{ width: "16%" }} />
+ </colgroup>
+ <thead>
+ <tr className="border-b border-gray-200">
+ <th className="textinfolabel font-medium uppercase text-xs tracking-wider py-2 px-2 text-left">
+ {t("common.instance")}
+ </th>
+ <th className="textinfolabel font-medium uppercase text-xs tracking-wider py-2 px-2 text-left">
+ {t("common.database")}
+ </th>
+ <th className="textinfolabel font-medium uppercase text-xs tracking-wider py-2 px-2 text-left">
+ {t("common.schema")}
+ </th>
+ <th className="textinfolabel font-medium uppercase text-xs tracking-wider py-2 px-2 text-left">
+ {t("common.table")}
+ </th>
+ <th className="textinfolabel font-medium uppercase text-xs tracking-wider py-2 px-2 text-left">
+ {t("common.columns")}
+ </th>
+ <th className="textinfolabel font-medium uppercase text-xs tracking-wider py-2 px-2 text-left">
+ {t("common.classification-level")}
+ </th>
+ </tr>
+ </thead>
+ <tbody>
+ {databaseResources.map((resource, idx) => {
+ const { databaseName } = extractDatabaseResourceName(
+ resource.databaseFullName
+ );
+ return (
+ <tr
+ key={idx}
+ className="border-b border-gray-200 last:border-b-0"
+ >
+ <td className="py-2 px-2 text-control-light">
+ <Tooltip content={displayInstance(resource)}>
+ <span className="block truncate">
+ {displayInstance(resource)}
+ </span>
+ </Tooltip>
+ </td>
+ <td className="py-2 px-2">
+ {isSentinel(databaseName) ? (
+ <span className="text-control-placeholder">
+ {t("database.all")}
+ </span>
+ ) : showDatabaseLink ? (
+ <Tooltip content={databaseName}>
+ <span
+ className="block truncate normal-link cursor-pointer"
+ onClick={() => handleDatabaseClick(resource)}
+ >
+ {databaseName}
+ </span>
+ </Tooltip>
+ ) : (
+ <Tooltip content={databaseName}>
+ <span className="block truncate text-control-light">
+ {databaseName}
+ </span>
+ </Tooltip>
+ )}
+ </td>
+ <td className="py-2 px-2 text-control-light">
+ {resource.schema ? (
+ <Tooltip content={resource.schema}>
+ <span className="block truncate">{resource.schema}</span>
+ </Tooltip>
+ ) : (
+ <span>-</span>
+ )}
+ </td>
+ <td className="py-2 px-2 text-control-light">
+ {resource.table ? (
+ <Tooltip content={resource.table}>
+ <span className="block truncate">{resource.table}</span>
+ </Tooltip>
+ ) : (
+ <span>-</span>
+ )}
+ </td>
+ <td className="py-2 px-2">
+ <ColumnCell columns={resource.columns} />
+ </td>
+ <td className="py-2 px-2">
+ <LevelBadge
+ level={classificationLevel?.value}
+ operator={classificationLevel?.operator}
+ noLimit={!classificationLevel}
+ />
+ </td>
+ </tr>
+ );
+ })}
+ </tbody>
+ </table>
+ </div>
+ );
+}
+
+// ============================================================
+// ColumnCell
+// ============================================================
+
+function ColumnCell({ columns }: { columns?: string[] }) {
+ const { t } = useTranslation();
+
+ if (!columns || columns.length === 0) {
+ return <span className="text-control-placeholder">-</span>;
+ }
+
+ const visible = columns.slice(0, COLUMN_VISIBLE_LIMIT);
+ const rest = columns.length - visible.length;
+ const text = visible.join(", ");
+
+ if (rest <= 0) {
+ return <span className="text-control-light">{text}</span>;
+ }
+
+ return (
+ <Tooltip
+ content={
+ <div className="flex flex-col gap-y-0.5">
+ {columns.map((col) => (
+ <span key={col}>{col}</span>
+ ))}
+ </div>
+ }
+ >
+ <span className="text-control-light">
+ {text}
+ <span className="text-control-placeholder ml-1">
+ {t("common.n-more", { n: rest })}
+ </span>
+ </span>
+ </Tooltip>
+ );
+}
+
+// ============================================================
+// ExemptionLevelCard
+// ============================================================
+
+function ExemptionLevelCard({
+ classificationLevel,
+}: {
+ classificationLevel?: ClassificationLevel;
+}) {
+ const { t } = useTranslation();
+
+ return (
+ <div className="flex items-center gap-x-6 px-4 py-3 bg-gray-50 rounded border border-gray-200">
+ <div className="flex items-center gap-x-2">
+ <span className="textinfolabel font-medium uppercase text-xs">
+ {t("common.scope")}
+ </span>
+ <span className="px-2 py-0.5 rounded text-xs bg-green-100 text-green-700 border border-green-200">
+ {t("database.all")}
+ </span>
+ </div>
+ <div className="flex items-center gap-x-2">
+ <span className="textinfolabel font-medium uppercase text-xs">
+ {t("common.classification-level")}
+ </span>
+ <LevelBadge
+ level={classificationLevel?.value}
+ operator={classificationLevel?.operator}
+ noLimit={!classificationLevel}
+ />
+ </div>
+ </div>
+ );
+}
+
+// ============================================================
+// LevelBadge
+// ============================================================
+
+const bgColorList = [
+ "bg-green-200",
+ "bg-yellow-200",
+ "bg-orange-300",
+ "bg-amber-500",
+ "bg-red-500",
+];
+
+function LevelBadge({
+ level,
+ operator = "<=",
+ noLimit = false,
+}: {
+ level?: number;
+ operator?: string;
+ noLimit?: boolean;
+}) {
+ const { t } = useTranslation();
+ const settingStore = useSettingV1Store();
+
+ const levelTitle = useVueState(() => {
+ if (level === undefined) return undefined;
+ const config = settingStore.classification[0];
+ return config?.levels?.find((l: { level: number }) => l.level === level)
+ ?.title;
+ });
+
+ const label = useMemo(() => {
+ if (noLimit || level === undefined)
+ return t("project.masking-exemption.all-levels");
+ const op = operatorDisplayLabel(operator);
+ return levelTitle ? `${op} ${level} (${levelTitle})` : `${op} ${level}`;
+ }, [noLimit, level, operator, levelTitle, t]);
+
+ const colorClass = useMemo(() => {
+ if (noLimit || level === undefined) {
+ return "bg-gray-200 text-gray-600";
+ }
+ const idx = Math.min(level - 1, bgColorList.length - 1);
+ const bg = bgColorList[Math.max(0, idx)] ?? "bg-gray-200";
+ return level >= 4 ? `${bg} text-white` : bg;
+ }, [noLimit, level]);
+
+ return (
+ <span
+ className={cn(
+ "px-1 py-0.5 rounded text-xs whitespace-nowrap",
+ colorClass
+ )}
+ >
+ {label}
+ </span>
+ );
+}
+
+// ============================================================
+// Utilities
+// ============================================================
+
+function hashString(str: string): number {
+ let hash = 0;
+ for (let i = 0; i < str.length; i++) {
+ hash = (hash << 5) - hash + str.charCodeAt(i);
+ hash |= 0;
+ }
+ return hash;
+}
diff --git a/frontend/src/router/dashboard/projectV1.ts b/frontend/src/router/dashboard/projectV1.ts
index 8bb9659769..37e62675ca 100644
--- a/frontend/src/router/dashboard/projectV1.ts
+++ b/frontend/src/router/dashboard/projectV1.ts
@@ -185,9 +185,11 @@ const projectV1Routes: RouteRecordRaw[] = [
{
path: "",
name: PROJECT_V1_ROUTE_MASKING_EXEMPTION,
- component: () =>
- import("@/views/project/ProjectMaskingExemption.vue"),
- props: true,
+ component: () => import("@/react/ReactPageMount.vue"),
+ props: (route: RouteLocationNormalized) => ({
+ page: "ProjectMaskingExemptionPage",
+ ...route.params,
+ }),
meta: {
requiredPermissionList: () => [
"bb.databases.get",
@@ -198,9 +200,11 @@ const projectV1Routes: RouteRecordRaw[] = [
{
path: "create",
name: PROJECT_V1_ROUTE_MASKING_EXEMPTION_CREATE,
- component: () =>
- import("@/views/project/ProjectMaskingExemptionCreate.vue"),
- props: true,
+ component: () => import("@/react/ReactPageMount.vue"),
+ props: (route: RouteLocationNormalized) => ({
+ page: "ProjectMaskingExemptionCreatePage",
+ ...route.params,
+ }),
meta: {
requiredPermissionList: () => [
"bb.policies.createMaskingExemptionPolicy",
diff --git a/frontend/src/views/project/ProjectMaskingExemption.vue b/frontend/src/views/project/ProjectMaskingExemption.vue
deleted file mode 100644
index 2b0f25cf6d..0000000000
--- a/frontend/src/views/project/ProjectMaskingExemption.vue
+++ /dev/null
@@ -1,272 +0,0 @@
-<template>
- <div class="flex flex-col">
- <div class="px-4 py-3">
- <div class="flex flex-row items-center gap-x-2 mb-2">
- <ExemptionSearchBar
- class="flex-1 min-w-0"
- :params="searchParams"
- :project-name="projectName"
- @update:params="searchParams = $event"
- />
-
- <PermissionGuardWrapper
- v-slot="slotProps"
- :project="project"
- :permissions="[
- 'bb.policies.createMaskingExemptionPolicy',
- 'bb.policies.updateMaskingExemptionPolicy',
- 'bb.databases.list',
- 'bb.databaseCatalogs.get',
- ]"
- >
- <NButton
- type="primary"
- :disabled="slotProps.disabled"
- @click="handleGrantClick"
- >
- <template #icon>
- <ShieldCheckIcon class="w-4" />
- <FeatureBadge
- :feature="PlanFeature.FEATURE_DATA_MASKING"
- class="text-white"
- />
- </template>
- {{ $t("project.masking-exemption.grant-exemption") }}
- </NButton>
- </PermissionGuardWrapper>
- </div>
- <ExemptionPresetTabs
- :params="searchParams"
- @update:params="searchParams = $event"
- />
- </div>
-
- <!-- Wide view: side-by-side.
- 11rem ≈ global nav (48px) + project selector (44px) + search bar (36px)
- + tabs (40px) + padding (8px). Both panels scroll independently within
- this fixed height. A flex-1 approach would require modifying shared
- layout ancestors (ProjectV1Layout, BodyLayout) which affects all pages. -->
- <template v-if="isWide">
- <div
- class="flex"
- :style="{ height: 'calc(100vh - 11rem)' }"
- >
- <ExemptionMemberList
- class="w-[360px] shrink-0 border-r border-gray-200 overflow-y-auto"
- :members="filteredMembers"
- :disabled="!hasPermission"
- :loading="exemptionsLoading"
- :selected-member-key="selectedMemberKey"
- @select="selectedMemberKey = $event"
- @revoke="handleRevoke"
- />
- <div class="flex-1 min-w-0 overflow-y-auto">
- <ExemptionDetailPanel
- v-if="!exemptionsLoading && selectedMemberData"
- :member="selectedMemberData"
- :disabled="!hasPermission"
- :show-database-link="showDatabaseLink"
- :database-filter="activeDatabaseFilter"
- @revoke="(grant) => handleRevoke(selectedMemberData!, grant)"
- />
- <div
- v-else-if="!exemptionsLoading"
- class="flex items-center justify-center h-full text-control-placeholder text-sm"
- >
- {{ $t("project.masking-exemption.no-exemptions") }}
- </div>
- </div>
- </div>
- </template>
-
- <!-- Narrow view: expandable list -->
- <template v-else>
- <ExemptionMemberList
- :members="filteredMembers"
- :disabled="!hasPermission"
- :loading="exemptionsLoading"
- :show-database-link="showDatabaseLink"
- :expandable="true"
- :database-filter="activeDatabaseFilter"
- @revoke="handleRevoke"
- />
- </template>
- </div>
-
- <FeatureModal
- :open="showFeatureModal"
- :feature="PlanFeature.FEATURE_DATA_MASKING"
- @cancel="showFeatureModal = false"
- />
-</template>
-
-<script lang="ts" setup>
-import { ShieldCheckIcon } from "lucide-vue-next";
-import { NButton, useDialog } from "naive-ui";
-import { computed, ref } from "vue";
-import { useI18n } from "vue-i18n";
-import { useRouter } from "vue-router";
-import { FeatureBadge, FeatureModal } from "@/components/FeatureGuard";
-import PermissionGuardWrapper from "@/components/Permission/PermissionGuardWrapper.vue";
-import ExemptionDetailPanel from "@/components/SensitiveData/ExemptionDetailPanel.vue";
-import ExemptionMemberList from "@/components/SensitiveData/ExemptionMemberList.vue";
-import ExemptionPresetTabs from "@/components/SensitiveData/ExemptionPresetTabs.vue";
-import ExemptionSearchBar from "@/components/SensitiveData/ExemptionSearchBar.vue";
-import { buildMemberSummary } from "@/components/SensitiveData/exemptionDataUtils";
-import type {
- ExemptionGrant,
- ExemptionMember,
-} from "@/components/SensitiveData/types";
-import { useExemptionData } from "@/components/SensitiveData/useExemptionData";
-import { useWideScreen } from "@/composables/useWideScreen";
-import { PROJECT_V1_ROUTE_MASKING_EXEMPTION_CREATE } from "@/router/dashboard/projectV1";
-import { hasFeature, useProjectByName } from "@/store";
-import { projectNamePrefix } from "@/store/modules/v1/common";
-import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";
-import {
- getValueFromSearchParams,
- hasProjectPermissionV2,
- type SearchParams,
-} from "@/utils";
-
-const props = defineProps<{
- projectId: string;
-}>();
-
-const { t } = useI18n(); // NOSONAR
-const router = useRouter(); // NOSONAR
-const $dialog = useDialog(); // NOSONAR
-
-const projectName = computed(() => `${projectNamePrefix}${props.projectId}`);
-const { project } = useProjectByName(projectName); // NOSONAR
-
-const isWide = useWideScreen(1024); // NOSONAR
-const showFeatureModal = ref(false);
-
-const showDatabaseLink = computed(() =>
- hasProjectPermissionV2(project.value, "bb.databases.get")
-);
-
-const hasPermission = computed(() =>
- hasProjectPermissionV2(
- project.value,
- "bb.policies.updateMaskingExemptionPolicy"
- )
-);
-
-const hasSensitiveDataFeature = computed(() =>
- hasFeature(PlanFeature.FEATURE_DATA_MASKING)
-);
-
-const searchParams = ref<SearchParams>({
- query: "",
- scopes: [{ id: "status", value: "active" }],
-});
-
-const {
- members,
- loading: exemptionsLoading,
- revokeGrant,
-} = useExemptionData(projectName); // NOSONAR
-
-const activeDatabaseFilter = computed(
- () => getValueFromSearchParams(searchParams.value, "database") || undefined
-);
-
-const isGrantActive = (g: ExemptionGrant): boolean =>
- !g.expirationTimestamp || g.expirationTimestamp > Date.now();
-
-// Rebuild an ExemptionMember with a subset of grants and recalculated summaries.
-const withFilteredGrants = (
- m: ExemptionMember,
- grants: ExemptionGrant[]
-): ExemptionMember => ({
- ...m,
- grants,
- ...buildMemberSummary(grants),
-});
-
-const filteredMembers = computed(() => {
- let result = members.value;
-
- // Free-text query: filter members by typed text (matches member identifier)
- const query = searchParams.value.query.trim().toLowerCase();
- if (query) {
- result = result.filter((m) => m.member.toLowerCase().includes(query));
- }
-
- const memberScope = getValueFromSearchParams(searchParams.value, "member");
- if (memberScope) {
- result = result.filter((m) =>
- m.member.toLowerCase().includes(memberScope.toLowerCase())
- );
- }
-
- // Status filter first: narrow grants before applying database filter.
- const statusScope = getValueFromSearchParams(searchParams.value, "status");
- if (statusScope === "active") {
- result = result
- .map((m) => withFilteredGrants(m, m.grants.filter(isGrantActive)))
- .filter((m) => m.grants.length > 0);
- } else if (statusScope === "expired") {
- result = result
- .map((m) =>
- withFilteredGrants(
- m,
- m.grants.filter((g) => !isGrantActive(g))
- )
- )
- .filter((m) => m.grants.length > 0);
- }
-
- // Database filter: prune grants at grant level (like status filter).
- // Global grants (no databaseResources) match any database filter.
- const dbScope = activeDatabaseFilter.value;
- if (dbScope) {
- const matchesDb = (g: ExemptionGrant) =>
- !g.databaseResources ||
- g.databaseResources.length === 0 ||
- g.databaseResources.some((r) => r.databaseFullName === dbScope);
- result = result
- .map((m) => withFilteredGrants(m, m.grants.filter(matchesDb)))
- .filter((m) => m.grants.length > 0);
- }
-
- return result;
-});
-
-const selectedMemberKey = ref("");
-
-const selectedMemberData = computed(() =>
- filteredMembers.value.find((m) => m.member === selectedMemberKey.value)
-);
-
-const handleGrantClick = () => {
- if (!hasSensitiveDataFeature.value) {
- showFeatureModal.value = true;
- return;
- }
- router.push({
- name: PROJECT_V1_ROUTE_MASKING_EXEMPTION_CREATE,
- });
-};
-
-const stripMemberPrefix = (raw: string): string => {
- const idx = raw.indexOf(":");
- return idx >= 0 ? raw.substring(idx + 1) : raw;
-};
-
-const handleRevoke = (member: ExemptionMember, grant: ExemptionGrant) => {
- $dialog.warning({
- title: t("common.warning"),
- content: t("project.masking-exemption.revoke-exemption-title", {
- member: stripMemberPrefix(member.member),
- }),
- negativeText: t("common.cancel"),
- positiveText: t("common.confirm"),
- onPositiveClick: async () => {
- await revokeGrant(member, grant);
- },
- });
-};
-</script>
diff --git a/frontend/src/views/project/ProjectMaskingExemptionCreate.vue b/frontend/src/views/project/ProjectMaskingExemptionCreate.vue
deleted file mode 100644
index ed7d24c80f..0000000000
--- a/frontend/src/views/project/ProjectMaskingExemptionCreate.vue
+++ /dev/null
@@ -1,26 +0,0 @@
-<template>
- <GrantAccessForm
- class="pt-4"
- :title="$t('project.masking-exemption.grant-exemption')"
- :column-list="[]"
- :project-name="project.name"
- @dismiss="() => router.back()"
- />
-</template>
-
-<script lang="tsx" setup>
-import { computed } from "vue";
-import { useRouter } from "vue-router";
-import GrantAccessForm from "@/components/SensitiveData/GrantAccessForm.vue";
-import { useProjectByName } from "@/store";
-import { projectNamePrefix } from "@/store/modules/v1/common";
-
-const props = defineProps<{
- projectId: string;
-}>();
-
-const { project } = useProjectByName(
- computed(() => `${projectNamePrefix}${props.projectId}`)
-);
-const router = useRouter();
-</script>