Skip to content

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

feat(masking-exemption): redesign exemption list page with classification level support (#19743)

zchpeter571a4c8640f1
diff --git a/.sonarcloud.properties b/.sonarcloud.properties
index eab3febdb1..36617e2e94 100644
--- a/.sonarcloud.properties
+++ b/.sonarcloud.properties
@@ -29,7 +29,7 @@ sonar.sourceEncoding=UTF-8
# Suppress false-positive security hotspots that travel with the codebase.
# These have been triaged and confirmed safe. Using sonar.issue.ignore so
# any fork or downstream SonarCloud scan also benefits.
-sonar.issue.ignore.multicriteria=fp_sync_sql,fp_route_creds,fp_stats_explain,fp_dump_sql,fp_role_sql
+sonar.issue.ignore.multicriteria=fp_sync_sql,fp_route_creds,fp_stats_explain,fp_dump_sql,fp_role_sql,fp_cognitive_ts,fp_cognitive_go
# go:S2077 (SQL Injection) in db plugin sync.go files.
# These files query system catalogs (information_schema, pg_catalog, sys.*) using
@@ -62,6 +62,14 @@ sonar.issue.ignore.multicriteria.fp_dump_sql.resourceKey=backend/plugin/db/*/dum
sonar.issue.ignore.multicriteria.fp_role_sql.ruleKey=go:S2077
sonar.issue.ignore.multicriteria.fp_role_sql.resourceKey=backend/plugin/db/*/role.go
+# Cognitive Complexity (S3776) — disabled for this repository.
+# Bytebase has complex domain logic (CEL parsing, policy evaluation, SQL generation)
+# where high cognitive complexity is inherent and not a code quality issue.
+sonar.issue.ignore.multicriteria.fp_cognitive_ts.ruleKey=typescript:S3776
+sonar.issue.ignore.multicriteria.fp_cognitive_ts.resourceKey=**/*
+sonar.issue.ignore.multicriteria.fp_cognitive_go.ruleKey=go:S3776
+sonar.issue.ignore.multicriteria.fp_cognitive_go.resourceKey=**/*
+
# Exclusions for copy-paste detection
sonar.cpd.exclusions=\
action/**/*_test.go,\
diff --git a/frontend/src/components/ExprEditor/components/OperatorSelect.vue b/frontend/src/components/ExprEditor/components/OperatorSelect.vue
index b97be726d6..0775ed5a33 100644
--- a/frontend/src/components/ExprEditor/components/OperatorSelect.vue
+++ b/frontend/src/components/ExprEditor/components/OperatorSelect.vue
@@ -18,6 +18,7 @@ import {
type ConditionExpr,
type ConditionOperator,
type Operator,
+ operatorDisplayLabel,
} from "@/plugins/cel";
import { useExprEditorContext } from "../context";
import { getOperatorListByFactor } from "./common";
@@ -42,31 +43,17 @@ const factor = computed(() => {
return props.expr.args[0];
});
-const OPERATOR_DICT = new Map([
- ["_==_", "=="],
- ["_!=_", "!="],
- ["_<_", "<"],
- ["_<=_", "≤"],
- ["_>=_", "≥"],
- ["_>_", ">"],
- ["@not_in", "not in"],
- ["@not_contains", "not contains"],
-]);
-
const options = computed(() => {
const operators = getOperatorListByFactor(
factor.value,
factorOperatorOverrideMap.value
);
-
- const mapOption = (op: Operator): SelectOption => {
- const label = OPERATOR_DICT.get(op) ?? op.replace(/^@/g, "");
- return {
- label,
+ return operators.map(
+ (op: Operator): SelectOption => ({
+ label: operatorDisplayLabel(op),
value: op,
- };
- };
- return operators.map(mapOption);
+ })
+ );
});
// normalize operator when factor changed
diff --git a/frontend/src/components/SensitiveData/ExemptionDetailPanel.vue b/frontend/src/components/SensitiveData/ExemptionDetailPanel.vue
new file mode 100644
index 0000000000..300e3ad0f4
--- /dev/null
+++ b/frontend/src/components/SensitiveData/ExemptionDetailPanel.vue
@@ -0,0 +1,100 @@
+<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
new file mode 100644
index 0000000000..150286e16b
--- /dev/null
+++ b/frontend/src/components/SensitiveData/ExemptionGrantSection.vue
@@ -0,0 +1,121 @@
+<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
new file mode 100644
index 0000000000..f3a4b6e54b
--- /dev/null
+++ b/frontend/src/components/SensitiveData/ExemptionLevelCard.vue
@@ -0,0 +1,32 @@
+<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
new file mode 100644
index 0000000000..a238f657fb
--- /dev/null
+++ b/frontend/src/components/SensitiveData/ExemptionMemberItem.vue
@@ -0,0 +1,137 @@
+<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
new file mode 100644
index 0000000000..930ac595a2
--- /dev/null
+++ b/frontend/src/components/SensitiveData/ExemptionMemberList.vue
@@ -0,0 +1,105 @@
+<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
new file mode 100644
index 0000000000..45ea23c094
--- /dev/null
+++ b/frontend/src/components/SensitiveData/ExemptionPresetTabs.vue
@@ -0,0 +1,55 @@
+<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
new file mode 100644
index 0000000000..c6175a350d
--- /dev/null
+++ b/frontend/src/components/SensitiveData/ExemptionResourceTable.vue
@@ -0,0 +1,197 @@
+<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
new file mode 100644
index 0000000000..18df5ca318
--- /dev/null
+++ b/frontend/src/components/SensitiveData/ExemptionSearchBar.vue
@@ -0,0 +1,32 @@
+<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/GrantAccessForm.vue b/frontend/src/components/SensitiveData/GrantAccessForm.vue
index 71dc06f174..c2d517f2ed 100644
--- a/frontend/src/components/SensitiveData/GrantAccessForm.vue
+++ b/frontend/src/components/SensitiveData/GrantAccessForm.vue
@@ -100,6 +100,7 @@ import {
import { Setting_SettingName } from "@/types/proto-es/v1/setting_service_pb";
import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";
import { batchConvertParsedExprToCELString } from "@/utils";
+import { rewriteResourceDatabase } from "./exemptionDataUtils";
import type { SensitiveColumn } from "./types";
import {
convertSensitiveColumnToDatabaseResource,
@@ -202,7 +203,12 @@ const getPendingUpdatePolicy = async (
if (expr) {
const parsedExpr = await buildCELExpr(expr);
if (parsedExpr) {
- const [celString] = await batchConvertParsedExprToCELString([parsedExpr]);
+ let [celString] = await batchConvertParsedExprToCELString([parsedExpr]);
+ // The expression editor uses `resource.database` as a convenience factor
+ // (e.g., resource.database == "instances/X/databases/Y"), but the backend
+ // masking exemption CEL evaluator only supports resource.instance_id and
+ // resource.database_name. Rewrite to the backend-compatible form.
+ celString = rewriteResourceDatabase(celString);
const parts = [celString, ...extraExpressions].filter((e) => e);
exemptions.push(
create(MaskingExemptionPolicy_ExemptionSchema, {
diff --git a/frontend/src/components/SensitiveData/LevelBadge.vue b/frontend/src/components/SensitiveData/LevelBadge.vue
new file mode 100644
index 0000000000..250a8d18f6
--- /dev/null
+++ b/frontend/src/components/SensitiveData/LevelBadge.vue
@@ -0,0 +1,62 @@
+<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/MaskingExceptionUserTable.vue b/frontend/src/components/SensitiveData/MaskingExceptionUserTable.vue
deleted file mode 100644
index 2b3fdd8b49..0000000000
--- a/frontend/src/components/SensitiveData/MaskingExceptionUserTable.vue
+++ /dev/null
@@ -1,463 +0,0 @@
-<template>
- <NDataTable
- :size="size"
- :columns="accessTableColumns"
- :data="filteredList"
- :row-key="(row: AccessUser) => row.key"
- :bordered="false"
- :striped="true"
- :loading="!ready || state.loading"
- :max-height="'calc(100vh - 15rem)'"
- virtual-scroll
- />
-</template>
-
-<script lang="tsx" setup>
-import { create } from "@bufbuild/protobuf";
-import { orderBy } from "lodash-es";
-import { TrashIcon } from "lucide-vue-next";
-import type { DataTableColumn } from "naive-ui";
-import { NDataTable, NDatePicker, NEllipsis, useDialog } from "naive-ui";
-import type { VNodeChild } from "vue";
-import { computed, h, reactive, watchEffect } from "vue";
-import { useI18n } from "vue-i18n";
-import { useRouter } from "vue-router";
-import GroupNameCell from "@/components/User/Settings/UserDataTableByGroup/cells/GroupNameCell.vue";
-import { MiniActionButton } from "@/components/v2";
-import { UserLink } from "@/components/v2/Model/cells";
-import {
- composePolicyBindings,
- extractUserEmail,
- pushNotification,
- useGroupStore,
- usePolicyByParentAndType,
- usePolicyV1Store,
-} from "@/store";
-import { type DatabaseResource, 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 type { Project } from "@/types/proto-es/v1/project_service_pb";
-import { hasProjectPermissionV2 } from "@/utils";
-import {
- batchConvertFromCELString,
- type ConditionExpression,
-} from "@/utils/issue/cel";
-import { type AccessUser } from "./types";
-
-interface LocalState {
- loading: boolean;
- processing: boolean;
- rawAccessList: AccessUser[];
-}
-
-const props = defineProps<{
- size: "small" | "medium";
- disabled: boolean;
- project: Project;
- showDatabaseColumn: boolean;
- filterAccessUser: (accessUser: AccessUser) => boolean;
-}>();
-
-const state = reactive<LocalState>({
- loading: true,
- processing: false,
- rawAccessList: [],
-});
-const { t } = useI18n();
-const router = useRouter();
-const groupStore = useGroupStore();
-const policyStore = usePolicyV1Store();
-const $dialog = useDialog();
-
-const hasGetDatabasePermission = computed(() =>
- hasProjectPermissionV2(props.project, "bb.databases.get")
-);
-
-const { policy, ready } = usePolicyByParentAndType(
- computed(() => ({
- parentPath: props.project.name,
- policyType: PolicyType.MASKING_EXEMPTION,
- }))
-);
-
-const filteredList = computed(() =>
- state.rawAccessList.filter(props.filterAccessUser)
-);
-
-const renderDatabaseResource = (res: DatabaseResource): VNodeChild => {
- return (
- <div class="flex flex-col gap-y-0.5 text-sm textinfo">
- <div class="flex items-center gap-x-1">
- <span class="font-medium">{`${t("common.database")}:`}</span>
- {hasGetDatabasePermission.value ? (
- <span
- class="normal-link hover:underline cursor-pointer"
- onClick={() => {
- const query: Record<string, string> = {};
- if (res.schema) query.schema = res.schema;
- if (res.table) query.table = res.table;
- router.push({ path: res.databaseFullName, query });
- }}
- >
- {res.databaseFullName}
- </span>
- ) : (
- <span>{res.databaseFullName}</span>
- )}
- </div>
- {res.schema && (
- <div class="flex items-center gap-x-1">
- <span class="font-medium">{`${t("common.schema")}:`}</span>
- <span>{res.schema}</span>
- </div>
- )}
- {res.table && (
- <div class="flex items-center gap-x-1">
- <span class="font-medium">{`${t("common.table")}:`}</span>
- <span>{res.table}</span>
- </div>
- )}
- {res.columns && res.columns.length > 0 && (
- <div class="flex items-center gap-x-1">
- <span class="font-medium">{`${t("database.columns")}:`}</span>
- <span>{res.columns.join(", ")}</span>
- </div>
- )}
- </div>
- );
-};
-
-const getConditionDisplay = (access: AccessUser): VNodeChild => {
- if (!access.databaseResources) {
- // No parseable database resources — show raw CEL or "All".
- if (access.conditionExpression) {
- return (
- <NEllipsis class="text-sm font-mono textinfo">
- {access.conditionExpression}
- </NEllipsis>
- );
- }
- return <div class="textinfo">{t("database.all")}</div>;
- }
-
- return (
- <div class="flex flex-col gap-y-2">
- {access.databaseResources.map((res) => renderDatabaseResource(res))}
- </div>
- );
-};
-
-const expirationTimeRegex = /request\.time\s*<\s*timestamp\("(.+)?"\)/;
-
-// Extract the condition portion of a CEL expression, excluding request.time.
-const getConditionExpression = (expression: string): string => {
- if (!expression) return "";
- return expression
- .split(" && ")
- .filter((part) => !part.match(expirationTimeRegex))
- .join(" && ");
-};
-
-const getAccessUsers = (
- exception: MaskingExemptionPolicy_Exemption,
- condition: ConditionExpression
-): AccessUser[] => {
- let expirationTimestamp: number | undefined;
- const expression = exception.condition?.expression ?? "";
- const description = exception.condition?.description ?? "";
- const matches = expirationTimeRegex.exec(expression);
- if (matches) {
- expirationTimestamp = new Date(matches[1]).getTime();
- }
-
- const conditionExpression = getConditionExpression(expression);
-
- const result: AccessUser[] = [];
- for (const member of exception.members) {
- const access: AccessUser = {
- type: member.startsWith(groupBindingPrefix) ? "group" : "user",
- member,
- key: `${member}:${expression}.${description}`,
- expirationTimestamp,
- rawExpression: expression,
- description,
- databaseResources:
- condition.databaseResources && condition.databaseResources.length > 0
- ? condition.databaseResources
- : undefined,
- conditionExpression,
- };
-
- result.push(access);
- }
-
- return result;
-};
-
-const updateAccessUserList = async () => {
- if (!ready.value) {
- return;
- }
-
- if (!policy.value || policy.value.policy?.case !== "maskingExemptionPolicy") {
- state.rawAccessList = [];
- state.loading = false;
- return;
- }
-
- 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);
-
- await composePolicyBindings(exemptions, true);
- for (let i = 0; i < exemptions.length; i++) {
- const exception = exemptions[i];
- const condition = conditionList[i];
-
- const items = getAccessUsers(exception, condition);
- for (const item of items) {
- memberMap.set(item.key, item);
- }
- }
-
- state.rawAccessList = orderBy(
- [...memberMap.values()],
- [(access) => (access.type === "user" ? 1 : 0), (access) => access.member],
- ["desc", "desc"]
- );
- state.loading = false;
-};
-
-watchEffect(updateAccessUserList);
-
-const accessTableColumns = computed(
- (): DataTableColumn<AccessUser & { hide?: boolean }>[] => {
- return [
- {
- type: "expand",
- expandable: (_: AccessUser) => true,
- hide: props.showDatabaseColumn,
- renderExpand: (item: AccessUser) => {
- return getConditionDisplay(item);
- },
- },
- {
- key: "member",
- title: t("common.members"),
- width: 180,
- render: (item: AccessUser) => {
- if (item.member.startsWith(groupBindingPrefix)) {
- const group = groupStore.getGroupByIdentifier(item.member);
- if (group) {
- return <GroupNameCell group={group} />;
- }
- } else {
- const email = extractUserEmail(item.member);
- return <UserLink title={email} email={email} />;
- }
- return <span>{item.member}</span>;
- },
- },
- {
- key: "condition",
- title: t("cel.condition.self"),
- hide: !props.showDatabaseColumn,
- render: (item: AccessUser) => {
- return getConditionDisplay(item);
- },
- },
- {
- key: "expire",
- title: t("common.expiration"),
- width: 220,
- render: (item: AccessUser) => {
- return (
- <NDatePicker
- value={item.expirationTimestamp}
- style={"width: 100%"}
- type={"datetime"}
- actions={["confirm"]}
- isDateDisabled={(date: number) => date < Date.now()}
- clearable={true}
- disabled={props.disabled}
- onUpdate:value={(val: number | undefined) =>
- onAccessControlUpdate(
- item,
- (item) => (item.expirationTimestamp = val)
- )
- }
- />
- );
- },
- },
- {
- key: "reason",
- title: t("common.reason"),
- width: 120,
- render: (item: AccessUser) => {
- return item.description;
- },
- },
- {
- key: "operation",
- title: "",
- hide: props.disabled,
- width: "4rem",
- render: (item: AccessUser) => {
- return h(
- MiniActionButton,
- {
- onClick: () => {
- revokeAccessAlert(item);
- },
- },
- {
- default: () => h(TrashIcon, { class: "w-4 h-4" }),
- }
- );
- },
- },
- ].filter((column) => !column.hide) as DataTableColumn<AccessUser>[];
- }
-);
-
-const revokeAccessAlert = (item: AccessUser) => {
- $dialog.warning({
- title: t("common.warning"),
- content: () => {
- return (
- <div class="flex flex-col gap-y-3">
- <div class="textlabel text-base!">
- {t("project.masking-exemption.revoke-exemption-title", {
- member: item.member,
- })}
- </div>
- {getConditionDisplay(item)}
- </div>
- );
- },
- style: "z-index: 100000",
- negativeText: t("common.cancel"),
- positiveText: t("common.confirm"),
- closeOnEsc: false,
- maskClosable: false,
- onPositiveClick: async () => {
- await onRemove(item);
- },
- });
-};
-
-const onRemove = async (item: AccessUser) => {
- const index = state.rawAccessList.findIndex((a) => a.key === item.key);
- if (index < 0) {
- return;
- }
- state.rawAccessList.splice(index, 1);
- await onSubmit();
-};
-
-const onAccessControlUpdate = async (
- item: AccessUser,
- callback: (item: AccessUser) => void
-) => {
- callback(item);
- await onSubmit();
-};
-
-const onSubmit = async () => {
- if (state.processing) {
- return;
- }
- state.processing = true;
-
- try {
- await updateExceptionPolicy();
- pushNotification({
- module: "bytebase",
- style: "SUCCESS",
- title: t("common.updated"),
- });
- } finally {
- state.processing = false;
- }
-};
-
-const updateExceptionPolicy = async () => {
- const policy = await policyStore.getOrFetchPolicyByParentAndType({
- parentPath: props.project.name,
- policyType: PolicyType.MASKING_EXEMPTION,
- });
- if (!policy) {
- return;
- }
-
- const expressionsMap = new Map<
- string,
- {
- description: string;
- members: string[];
- }
- >();
-
- for (const accessUser of state.rawAccessList) {
- const expressions = accessUser.rawExpression
- .split(" && ")
- .filter((expression) => expression);
- 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 exceptions = [];
- for (const [expression, { description, members }] of expressionsMap) {
- exceptions.push({
- members,
- condition: create(ExprSchema, {
- description: description,
- expression: expression,
- }),
- });
- }
-
- policy.policy = {
- case: "maskingExemptionPolicy",
- value: create(MaskingExemptionPolicySchema, {
- exemptions: exceptions,
- }),
- };
- await policyStore.upsertPolicy({
- parentPath: props.project.name,
- policy,
- });
-};
-</script>
diff --git a/frontend/src/components/SensitiveData/components/utils.ts b/frontend/src/components/SensitiveData/components/utils.ts
index 14e4e6c557..5b89aa63fd 100644
--- a/frontend/src/components/SensitiveData/components/utils.ts
+++ b/frontend/src/components/SensitiveData/components/utils.ts
@@ -18,7 +18,7 @@ export const getClassificationLevelOptions = () => {
return [];
}
return config.levels.map<ResourceSelectOption<unknown>>((l) => ({
- label: l.title,
+ label: `${l.level} (${l.title})`,
value: String(l.level),
}));
};
diff --git a/frontend/src/components/SensitiveData/exemptionDataUtils.test.ts b/frontend/src/components/SensitiveData/exemptionDataUtils.test.ts
new file mode 100644
index 0000000000..b435eeb8cc
--- /dev/null
+++ b/frontend/src/components/SensitiveData/exemptionDataUtils.test.ts
@@ -0,0 +1,1017 @@
+import { describe, expect, test, vi } from "vitest";
+
+vi.mock("@/plugins/i18n", () => ({
+ locale: { value: "en-US" },
+ t: (key: string, params?: Record<string, unknown>) => {
+ const map: Record<string, string> = {
+ "database.all": "All databases",
+ "common.schema": "Schema",
+ "common.table": "Table",
+ "project.masking-exemption.level": "level",
+ };
+ if (key === "common.n-more" && params?.n !== undefined)
+ return `+${params.n} more`;
+ return map[key] ?? key;
+ },
+}));
+
+import {
+ generateGrantTitle,
+ getConditionExpression,
+ groupByMember,
+ parseClassificationLevel,
+ parseExpirationTimestamp,
+ rewriteResourceDatabase,
+} from "./exemptionDataUtils";
+import type { AccessUser, ExemptionGrant } from "./types";
+
+describe("parseClassificationLevel", () => {
+ test("parses <= operator", () => {
+ const result = parseClassificationLevel(
+ "resource.classification_level <= 3"
+ );
+ expect(result).toEqual({ operator: "<=", value: 3 });
+ });
+
+ test("parses == operator", () => {
+ const result = parseClassificationLevel(
+ "resource.classification_level == 2"
+ );
+ expect(result).toEqual({ operator: "==", value: 2 });
+ });
+
+ test("parses < operator", () => {
+ const result = parseClassificationLevel(
+ "resource.classification_level < 4"
+ );
+ expect(result).toEqual({ operator: "<", value: 4 });
+ });
+
+ test("parses >= operator", () => {
+ const result = parseClassificationLevel(
+ "resource.classification_level >= 1"
+ );
+ expect(result).toEqual({ operator: ">=", value: 1 });
+ });
+
+ test("parses > operator", () => {
+ const result = parseClassificationLevel(
+ "resource.classification_level > 0"
+ );
+ expect(result).toEqual({ operator: ">", value: 0 });
+ });
+
+ test("parses != operator", () => {
+ const result = parseClassificationLevel(
+ "resource.classification_level != 5"
+ );
+ expect(result).toEqual({ operator: "!=", value: 5 });
+ });
+
+ test("handles extra whitespace around operator", () => {
+ const result = parseClassificationLevel(
+ "resource.classification_level <= 3"
+ );
+ expect(result).toEqual({ operator: "<=", value: 3 });
+ });
+
+ test("extracts level from a combined CEL expression", () => {
+ const result = parseClassificationLevel(
+ 'resource.instance_id == "prod" && resource.classification_level <= 3'
+ );
+ expect(result).toEqual({ operator: "<=", value: 3 });
+ });
+
+ test("returns undefined when no classification level present", () => {
+ const result = parseClassificationLevel(
+ 'resource.instance_id == "prod" && resource.database_name == "hr"'
+ );
+ expect(result).toBeUndefined();
+ });
+
+ test("returns undefined for empty string", () => {
+ expect(parseClassificationLevel("")).toBeUndefined();
+ });
+
+ test("handles multi-digit level values", () => {
+ const result = parseClassificationLevel(
+ "resource.classification_level <= 10"
+ );
+ expect(result).toEqual({ operator: "<=", value: 10 });
+ });
+});
+
+describe("getConditionExpression", () => {
+ test("strips request.time from expression", () => {
+ const result = getConditionExpression(
+ 'resource.instance_id == "prod" && request.time < timestamp("2026-04-15T00:00:00Z")'
+ );
+ expect(result).toBe('resource.instance_id == "prod"');
+ });
+
+ test("returns full expression when no request.time", () => {
+ const result = getConditionExpression(
+ 'resource.instance_id == "prod" && resource.database_name == "hr"'
+ );
+ expect(result).toBe(
+ 'resource.instance_id == "prod" && resource.database_name == "hr"'
+ );
+ });
+
+ test("returns empty string for empty input", () => {
+ expect(getConditionExpression("")).toBe("");
+ });
+
+ test("returns empty string when expression is only request.time", () => {
+ const result = getConditionExpression(
+ 'request.time < timestamp("2026-04-15T00:00:00Z")'
+ );
+ expect(result).toBe("");
+ });
+
+ test("handles extra whitespace in request.time", () => {
+ const result = getConditionExpression(
+ 'resource.instance_id == "prod" && request.time < timestamp("2026-04-15T00:00:00Z")'
+ );
+ expect(result).toBe('resource.instance_id == "prod"');
+ });
+});
+
+describe("parseExpirationTimestamp", () => {
+ test("extracts timestamp from request.time expression", () => {
+ const result = parseExpirationTimestamp(
+ 'resource.instance_id == "prod" && request.time < timestamp("2026-04-15T11:30:00.000Z")'
+ );
+ expect(result).toBe(new Date("2026-04-15T11:30:00.000Z").getTime());
+ });
+
+ test("returns undefined when no request.time present", () => {
+ const result = parseExpirationTimestamp('resource.instance_id == "prod"');
+ expect(result).toBeUndefined();
+ });
+
+ test("returns undefined for empty string", () => {
+ expect(parseExpirationTimestamp("")).toBeUndefined();
+ });
+
+ test("extracts timestamp when request.time is the only expression", () => {
+ const result = parseExpirationTimestamp(
+ 'request.time < timestamp("2026-12-31T23:59:59.000Z")'
+ );
+ expect(result).toBe(new Date("2026-12-31T23:59:59.000Z").getTime());
+ });
+});
+
+describe("groupByMember", () => {
+ const makeAccessUser = (overrides: Partial<AccessUser>): AccessUser => ({
+ type: "user",
+ member: "user:[email protected]",
+ rawExpression: "",
+ description: "",
+ conditionExpression: "",
+ ...overrides,
+ });
+
+ test("groups multiple exemptions for the same member", () => {
+ const users: AccessUser[] = [
+ makeAccessUser({
+ member: "user:[email protected]",
+ description: "Grant 1",
+ conditionExpression: 'resource.instance_id == "prod"',
+ }),
+ makeAccessUser({
+ member: "user:[email protected]",
+ description: "Grant 2",
+ conditionExpression: "resource.classification_level <= 3",
+ }),
+ ];
+
+ const result = groupByMember(users);
+ expect(result).toHaveLength(1);
+ expect(result[0].member).toBe("user:[email protected]");
+ expect(result[0].grants).toHaveLength(2);
+ // Latest created grant first (reversed order)
+ expect(result[0].grants[0].description).toBe("Grant 2");
+ expect(result[0].grants[1].description).toBe("Grant 1");
+ });
+
+ test("separates different members", () => {
+ const users: AccessUser[] = [
+ makeAccessUser({ member: "user:[email protected]" }),
+ makeAccessUser({ member: "user:[email protected]" }),
+ ];
+
+ const result = groupByMember(users);
+ expect(result).toHaveLength(2);
+ expect(
+ result.map((m) => m.member).sort((a, b) => a.localeCompare(b))
+ ).toEqual(["user:[email protected]", "user:[email protected]"]);
+ });
+
+ test("detects group type from member prefix", () => {
+ const users: AccessUser[] = [
+ makeAccessUser({
+ type: "group",
+ member: "group:[email protected]",
+ }),
+ ];
+
+ const result = groupByMember(users);
+ expect(result[0].type).toBe("group");
+ });
+
+ test("computes neverExpires=true when any grant has no expiration", () => {
+ const users: AccessUser[] = [
+ makeAccessUser({
+ member: "user:[email protected]",
+ expirationTimestamp: new Date("2026-04-15").getTime(),
+ }),
+ makeAccessUser({
+ member: "user:[email protected]",
+ expirationTimestamp: undefined,
+ }),
+ ];
+
+ const result = groupByMember(users);
+ expect(result[0].neverExpires).toBe(true);
+ });
+
+ test("computes neverExpires=false when all grants have expiration", () => {
+ const users: AccessUser[] = [
+ makeAccessUser({
+ member: "user:[email protected]",
+ expirationTimestamp: new Date("2026-04-15").getTime(),
+ }),
+ makeAccessUser({
+ member: "user:[email protected]",
+ expirationTimestamp: new Date("2026-06-30").getTime(),
+ }),
+ ];
+
+ const result = groupByMember(users);
+ expect(result[0].neverExpires).toBe(false);
+ });
+
+ test("computes nearestExpiration as earliest timestamp", () => {
+ const apr = new Date("2026-04-15").getTime();
+ const jun = new Date("2026-06-30").getTime();
+ const users: AccessUser[] = [
+ makeAccessUser({
+ member: "user:[email protected]",
+ expirationTimestamp: jun,
+ }),
+ makeAccessUser({
+ member: "user:[email protected]",
+ expirationTimestamp: apr,
+ }),
+ ];
+
+ const result = groupByMember(users);
+ expect(result[0].nearestExpiration).toBe(apr);
+ });
+
+ test("nearestExpiration is undefined when no grants have expiration", () => {
+ const users: AccessUser[] = [
+ makeAccessUser({
+ member: "user:[email protected]",
+ }),
+ ];
+
+ const result = groupByMember(users);
+ expect(result[0].nearestExpiration).toBeUndefined();
+ });
+
+ test("databaseNames has empty sentinel when no grants have databaseResources", () => {
+ const users: AccessUser[] = [
+ makeAccessUser({
+ member: "user:[email protected]",
+ conditionExpression: "resource.classification_level <= 3",
+ }),
+ ];
+
+ const result = groupByMember(users);
+ // Empty sentinel indicates "all databases" (grant has no specific resources)
+ expect(result[0].databaseNames).toEqual([""]);
+ });
+
+ test("extracts unique database names from resources", () => {
+ const users: AccessUser[] = [
+ makeAccessUser({
+ member: "user:[email protected]",
+ databaseResources: [
+ {
+ databaseFullName: "instances/prod/databases/hr_prod",
+ schema: "public",
+ table: "employee",
+ },
+ {
+ databaseFullName: "instances/prod/databases/hr_prod",
+ schema: "public",
+ table: "audit",
+ },
+ {
+ databaseFullName: "instances/dev/databases/test",
+ schema: "",
+ table: "",
+ },
+ ],
+ }),
+ ];
+
+ const result = groupByMember(users);
+ expect(result[0].databaseNames.sort((a, b) => a.localeCompare(b))).toEqual([
+ "hr_prod",
+ "test",
+ ]);
+ });
+
+ test("parses classification level into grant", () => {
+ const users: AccessUser[] = [
+ makeAccessUser({
+ member: "user:[email protected]",
+ conditionExpression:
+ 'resource.instance_id == "prod" && resource.classification_level <= 3',
+ }),
+ ];
+
+ const result = groupByMember(users);
+ expect(result[0].grants[0].classificationLevel).toEqual({
+ operator: "<=",
+ value: 3,
+ });
+ });
+
+ test("classificationLevel is undefined when not in expression", () => {
+ const users: AccessUser[] = [
+ makeAccessUser({
+ member: "user:[email protected]",
+ conditionExpression: 'resource.instance_id == "prod"',
+ }),
+ ];
+
+ const result = groupByMember(users);
+ expect(result[0].grants[0].classificationLevel).toBeUndefined();
+ });
+
+ test("handles empty input array", () => {
+ expect(groupByMember([])).toEqual([]);
+ });
+
+ test("does not merge grants — each exemption is its own card", () => {
+ const exp = new Date("2026-04-15").getTime();
+ const users: AccessUser[] = [
+ makeAccessUser({
+ member: "user:[email protected]",
+ description: "Production audit",
+ expirationTimestamp: exp,
+ databaseResources: [
+ {
+ databaseFullName: "instances/prod/databases/hr_prod",
+ schema: "public",
+ table: "audit",
+ },
+ ],
+ }),
+ makeAccessUser({
+ member: "user:[email protected]",
+ description: "Production audit",
+ expirationTimestamp: exp,
+ databaseResources: [
+ {
+ databaseFullName: "instances/prod/databases/hr_prod",
+ schema: "public",
+ table: "department",
+ },
+ ],
+ }),
+ makeAccessUser({
+ member: "user:[email protected]",
+ description: "Production audit",
+ expirationTimestamp: exp,
+ databaseResources: [
+ {
+ databaseFullName: "instances/prod/databases/hr_prod",
+ schema: "public",
+ table: "employee",
+ },
+ ],
+ }),
+ ];
+
+ const result = groupByMember(users);
+ expect(result).toHaveLength(1);
+ // No merging — each exemption is its own grant card
+ expect(result[0].grants).toHaveLength(3);
+ });
+
+ test("keeps overlapping resources as separate grants", () => {
+ const users: AccessUser[] = [
+ makeAccessUser({
+ member: "user:[email protected]",
+ description: "",
+ databaseResources: [
+ {
+ databaseFullName: "instances/prod/databases/hr_prod",
+ schema: "public",
+ table: "employee",
+ },
+ {
+ databaseFullName: "instances/prod/databases/hr_prod",
+ schema: "public",
+ table: "audit",
+ },
+ ],
+ }),
+ makeAccessUser({
+ member: "user:[email protected]",
+ description: "",
+ databaseResources: [
+ {
+ databaseFullName: "instances/prod/databases/hr_prod",
+ schema: "public",
+ table: "employee",
+ },
+ {
+ databaseFullName: "instances/prod/databases/hr_prod",
+ schema: "public",
+ table: "department",
+ },
+ ],
+ }),
+ ];
+
+ const result = groupByMember(users);
+ // No merging — each exemption keeps its own resources
+ expect(result[0].grants).toHaveLength(2);
+ expect(result[0].grants[0].databaseResources).toHaveLength(2);
+ expect(result[0].grants[1].databaseResources).toHaveLength(2);
+ });
+
+ test("keeps grants with different descriptions as separate cards", () => {
+ const users: AccessUser[] = [
+ makeAccessUser({
+ member: "user:[email protected]",
+ description: "Audit access",
+ databaseResources: [
+ {
+ databaseFullName: "instances/prod/databases/hr_prod",
+ schema: "public",
+ table: "audit",
+ },
+ ],
+ }),
+ makeAccessUser({
+ member: "user:[email protected]",
+ description: "Dev access",
+ databaseResources: [
+ {
+ databaseFullName: "instances/prod/databases/hr_prod",
+ schema: "public",
+ table: "employee",
+ },
+ ],
+ }),
+ ];
+
+ const result = groupByMember(users);
+ expect(result[0].grants).toHaveLength(2);
+ });
+
+ test("does NOT merge grants with different expirations", () => {
+ const users: AccessUser[] = [
+ makeAccessUser({
+ member: "user:[email protected]",
+ description: "Same reason",
+ expirationTimestamp: new Date("2026-04-15").getTime(),
+ databaseResources: [
+ {
+ databaseFullName: "instances/prod/databases/hr_prod",
+ schema: "public",
+ table: "audit",
+ },
+ ],
+ }),
+ makeAccessUser({
+ member: "user:[email protected]",
+ description: "Same reason",
+ expirationTimestamp: new Date("2026-06-30").getTime(),
+ databaseResources: [
+ {
+ databaseFullName: "instances/prod/databases/hr_prod",
+ schema: "public",
+ table: "employee",
+ },
+ ],
+ }),
+ ];
+
+ const result = groupByMember(users);
+ expect(result[0].grants).toHaveLength(2);
+ });
+
+ test("does NOT merge grants with different classification levels", () => {
+ const users: AccessUser[] = [
+ makeAccessUser({
+ member: "user:[email protected]",
+ description: "",
+ conditionExpression:
+ 'resource.instance_id == "prod" && resource.classification_level <= 3',
+ databaseResources: [
+ {
+ databaseFullName: "instances/prod/databases/hr_prod",
+ schema: "public",
+ table: "audit",
+ },
+ ],
+ }),
+ makeAccessUser({
+ member: "user:[email protected]",
+ description: "",
+ conditionExpression:
+ 'resource.instance_id == "prod" && resource.classification_level <= 5',
+ databaseResources: [
+ {
+ databaseFullName: "instances/prod/databases/hr_prod",
+ schema: "public",
+ table: "employee",
+ },
+ ],
+ }),
+ ];
+
+ const result = groupByMember(users);
+ expect(result[0].grants).toHaveLength(2);
+ });
+
+ test("keeps level-only grants as separate cards even with same description", () => {
+ const users: AccessUser[] = [
+ makeAccessUser({
+ member: "user:[email protected]",
+ description: "Level access",
+ conditionExpression: "resource.classification_level <= 3",
+ }),
+ makeAccessUser({
+ member: "user:[email protected]",
+ description: "Level access",
+ conditionExpression: "resource.classification_level <= 3",
+ }),
+ ];
+
+ const result = groupByMember(users);
+ // No merging — each exemption is its own card
+ expect(result[0].grants).toHaveLength(2);
+ });
+});
+
+describe("generateGrantTitle", () => {
+ const makeGrant = (overrides: Partial<ExemptionGrant>): ExemptionGrant => ({
+ id: "test",
+ description: "",
+ rawExpression: "",
+ conditionExpression: "",
+ ...overrides,
+ });
+
+ // --- No databases ---
+
+ test("no resources, no level → All databases", () => {
+ expect(generateGrantTitle(makeGrant({}))).toBe("All databases");
+ });
+
+ test("no resources, with level", () => {
+ expect(
+ generateGrantTitle(
+ makeGrant({ classificationLevel: { operator: "<=", value: 3 } })
+ )
+ ).toBe("All databases, level ≤ 3");
+ });
+
+ // --- Multiple databases ---
+
+ test("2 databases", () => {
+ expect(
+ generateGrantTitle(
+ makeGrant({
+ databaseResources: [
+ {
+ databaseFullName: "instances/a/databases/bbdev",
+ schema: "",
+ table: "",
+ },
+ {
+ databaseFullName: "instances/a/databases/hr_prod",
+ schema: "",
+ table: "",
+ },
+ ],
+ })
+ )
+ ).toBe("bbdev, hr_prod");
+ });
+
+ test("3 databases", () => {
+ expect(
+ generateGrantTitle(
+ makeGrant({
+ databaseResources: [
+ {
+ databaseFullName: "instances/a/databases/bbdev",
+ schema: "",
+ table: "",
+ },
+ {
+ databaseFullName: "instances/a/databases/hr_prod",
+ schema: "",
+ table: "",
+ },
+ {
+ databaseFullName: "instances/a/databases/test",
+ schema: "",
+ table: "",
+ },
+ ],
+ })
+ )
+ ).toBe("bbdev, hr_prod +1 more");
+ });
+
+ test("2 databases with level", () => {
+ expect(
+ generateGrantTitle(
+ makeGrant({
+ databaseResources: [
+ {
+ databaseFullName: "instances/a/databases/bbdev",
+ schema: "",
+ table: "",
+ },
+ {
+ databaseFullName: "instances/a/databases/hr_prod",
+ schema: "",
+ table: "",
+ },
+ ],
+ classificationLevel: { operator: "<=", value: 3 },
+ })
+ )
+ ).toBe("bbdev, hr_prod, level ≤ 3");
+ });
+
+ // --- Single database, single path (drill down) ---
+
+ test("1 db, no schema, no table", () => {
+ expect(
+ generateGrantTitle(
+ makeGrant({
+ databaseResources: [
+ {
+ databaseFullName: "instances/a/databases/hr_prod",
+ schema: "",
+ table: "",
+ },
+ ],
+ })
+ )
+ ).toBe("hr_prod");
+ });
+
+ test("1 db, 1 schema, no table → show schema keyword", () => {
+ expect(
+ generateGrantTitle(
+ makeGrant({
+ databaseResources: [
+ {
+ databaseFullName: "instances/a/databases/hr_prod",
+ schema: "public",
+ table: "",
+ },
+ ],
+ })
+ )
+ ).toBe("hr_prod (schema public)");
+ });
+
+ test("1 db, 1 schema, 1 table → dot notation", () => {
+ expect(
+ generateGrantTitle(
+ makeGrant({
+ databaseResources: [
+ {
+ databaseFullName: "instances/a/databases/hr_prod",
+ schema: "public",
+ table: "audit",
+ },
+ ],
+ })
+ )
+ ).toBe("hr_prod (public.audit)");
+ });
+
+ test("1 db, 1 schema, 1 table, 1 column → full dot path", () => {
+ expect(
+ generateGrantTitle(
+ makeGrant({
+ databaseResources: [
+ {
+ databaseFullName: "instances/a/databases/hr_prod",
+ schema: "public",
+ table: "employee",
+ columns: ["emp_no"],
+ },
+ ],
+ })
+ )
+ ).toBe("hr_prod (public.employee.emp_no)");
+ });
+
+ test("1 db, 1 schema, 1 table, 2 columns → colon then list", () => {
+ expect(
+ generateGrantTitle(
+ makeGrant({
+ databaseResources: [
+ {
+ databaseFullName: "instances/a/databases/hr_prod",
+ schema: "public",
+ table: "employee",
+ columns: ["emp_no", "name"],
+ },
+ ],
+ })
+ )
+ ).toBe("hr_prod (public.employee: emp_no, name)");
+ });
+
+ test("1 db, 1 schema, 1 table, 3+ columns → colon then 2 + more", () => {
+ expect(
+ generateGrantTitle(
+ makeGrant({
+ databaseResources: [
+ {
+ databaseFullName: "instances/a/databases/hr_prod",
+ schema: "public",
+ table: "employee",
+ columns: ["emp_no", "name", "salary", "dept"],
+ },
+ ],
+ })
+ )
+ ).toBe("hr_prod (public.employee: emp_no, name +2 more)");
+ });
+
+ test("1 db, no schema, 1 table → table keyword", () => {
+ expect(
+ generateGrantTitle(
+ makeGrant({
+ databaseResources: [
+ {
+ databaseFullName: "instances/a/databases/hr_prod",
+ schema: "",
+ table: "employee",
+ },
+ ],
+ })
+ )
+ ).toBe("hr_prod (table employee)");
+ });
+
+ test("1 db, no schema, 1 table, 1 column → table.column", () => {
+ expect(
+ generateGrantTitle(
+ makeGrant({
+ databaseResources: [
+ {
+ databaseFullName: "instances/a/databases/hr_prod",
+ schema: "",
+ table: "employee",
+ columns: ["emp_no"],
+ },
+ ],
+ })
+ )
+ ).toBe("hr_prod (employee.emp_no)");
+ });
+
+ // --- Single database, branching (multiple at some level) ---
+
+ test("1 db, 2 schemas → comma list, stop", () => {
+ expect(
+ generateGrantTitle(
+ makeGrant({
+ databaseResources: [
+ {
+ databaseFullName: "instances/a/databases/hr_prod",
+ schema: "public",
+ table: "",
+ },
+ {
+ databaseFullName: "instances/a/databases/hr_prod",
+ schema: "test",
+ table: "",
+ },
+ ],
+ })
+ )
+ ).toBe("hr_prod (public, test)");
+ });
+
+ test("1 db, 3 schemas → 2 + more", () => {
+ expect(
+ generateGrantTitle(
+ makeGrant({
+ databaseResources: [
+ {
+ databaseFullName: "instances/a/databases/hr_prod",
+ schema: "public",
+ table: "",
+ },
+ {
+ databaseFullName: "instances/a/databases/hr_prod",
+ schema: "test",
+ table: "",
+ },
+ {
+ databaseFullName: "instances/a/databases/hr_prod",
+ schema: "audit",
+ table: "",
+ },
+ ],
+ })
+ )
+ ).toBe("hr_prod (public, test +1 more)");
+ });
+
+ test("1 db, 1 schema, 2 tables → colon then list", () => {
+ expect(
+ generateGrantTitle(
+ makeGrant({
+ databaseResources: [
+ {
+ databaseFullName: "instances/a/databases/hr_prod",
+ schema: "public",
+ table: "audit",
+ },
+ {
+ databaseFullName: "instances/a/databases/hr_prod",
+ schema: "public",
+ table: "dept",
+ },
+ ],
+ })
+ )
+ ).toBe("hr_prod (public: audit, dept)");
+ });
+
+ test("1 db, 1 schema, 3 tables → colon then 2 + more", () => {
+ expect(
+ generateGrantTitle(
+ makeGrant({
+ databaseResources: [
+ {
+ databaseFullName: "instances/a/databases/hr_prod",
+ schema: "public",
+ table: "audit",
+ },
+ {
+ databaseFullName: "instances/a/databases/hr_prod",
+ schema: "public",
+ table: "dept",
+ },
+ {
+ databaseFullName: "instances/a/databases/hr_prod",
+ schema: "public",
+ table: "employee",
+ },
+ ],
+ })
+ )
+ ).toBe("hr_prod (public: audit, dept +1 more)");
+ });
+
+ test("1 db, no schema, 2 tables → comma list", () => {
+ expect(
+ generateGrantTitle(
+ makeGrant({
+ databaseResources: [
+ {
+ databaseFullName: "instances/a/databases/hr_prod",
+ schema: "",
+ table: "audit",
+ },
+ {
+ databaseFullName: "instances/a/databases/hr_prod",
+ schema: "",
+ table: "dept",
+ },
+ ],
+ })
+ )
+ ).toBe("hr_prod (audit, dept)");
+ });
+
+ test("1 db, no schema, 4 tables → 2 + more", () => {
+ expect(
+ generateGrantTitle(
+ makeGrant({
+ databaseResources: [
+ {
+ databaseFullName: "instances/a/databases/hr_prod",
+ schema: "",
+ table: "a",
+ },
+ {
+ databaseFullName: "instances/a/databases/hr_prod",
+ schema: "",
+ table: "b",
+ },
+ {
+ databaseFullName: "instances/a/databases/hr_prod",
+ schema: "",
+ table: "c",
+ },
+ {
+ databaseFullName: "instances/a/databases/hr_prod",
+ schema: "",
+ table: "d",
+ },
+ ],
+ })
+ )
+ ).toBe("hr_prod (a, b +2 more)");
+ });
+
+ // --- With level suffix ---
+
+ test("single path with level", () => {
+ expect(
+ generateGrantTitle(
+ makeGrant({
+ databaseResources: [
+ {
+ databaseFullName: "instances/a/databases/hr_prod",
+ schema: "public",
+ table: "audit",
+ },
+ ],
+ classificationLevel: { operator: "<=", value: 3 },
+ })
+ )
+ ).toBe("hr_prod (public.audit), level ≤ 3");
+ });
+
+ test("branching with level", () => {
+ expect(
+ generateGrantTitle(
+ makeGrant({
+ databaseResources: [
+ {
+ databaseFullName: "instances/a/databases/hr_prod",
+ schema: "public",
+ table: "audit",
+ },
+ {
+ databaseFullName: "instances/a/databases/hr_prod",
+ schema: "public",
+ table: "dept",
+ },
+ ],
+ classificationLevel: { operator: "==", value: 1 },
+ })
+ )
+ ).toBe("hr_prod (public: audit, dept), level = 1");
+ });
+});
+
+describe("rewriteResourceDatabase", () => {
+ test("rewrites single resource.database condition", () => {
+ const input =
+ 'resource.database == "instances/prod-instance/databases/hr_prod"';
+ expect(rewriteResourceDatabase(input)).toBe(
+ 'resource.instance_id == "prod-instance" && resource.database_name == "hr_prod"'
+ );
+ });
+
+ test("rewrites multiple resource.database conditions", () => {
+ const input =
+ '(resource.database == "instances/a/databases/db1") || (resource.database == "instances/b/databases/db2")';
+ expect(rewriteResourceDatabase(input)).toBe(
+ '(resource.instance_id == "a" && resource.database_name == "db1") || (resource.instance_id == "b" && resource.database_name == "db2")'
+ );
+ });
+
+ test("preserves expressions without resource.database", () => {
+ const input = "resource.classification_level <= 3";
+ expect(rewriteResourceDatabase(input)).toBe(input);
+ });
+
+ test("handles mixed conditions", () => {
+ const input =
+ 'resource.database == "instances/prod/databases/users" && resource.classification_level <= 2';
+ expect(rewriteResourceDatabase(input)).toBe(
+ 'resource.instance_id == "prod" && resource.database_name == "users" && resource.classification_level <= 2'
+ );
+ });
+
+ test("handles empty string", () => {
+ expect(rewriteResourceDatabase("")).toBe("");
+ });
+});
diff --git a/frontend/src/components/SensitiveData/exemptionDataUtils.ts b/frontend/src/components/SensitiveData/exemptionDataUtils.ts
new file mode 100644
index 0000000000..41151f2e3d
--- /dev/null
+++ b/frontend/src/components/SensitiveData/exemptionDataUtils.ts
@@ -0,0 +1,257 @@
+import { t } from "@/plugins/i18n";
+import type {
+ AccessUser,
+ ClassificationLevel,
+ ExemptionGrant,
+ ExemptionMember,
+} from "./types";
+
+const classificationLevelRegex =
+ /resource\.classification_level\s*(\S+)\s*(\d+)/;
+
+export function parseClassificationLevel(
+ conditionExpression: string
+): ClassificationLevel | undefined {
+ const match = classificationLevelRegex.exec(conditionExpression);
+ if (!match) return undefined;
+ return { operator: match[1], value: parseInt(match[2], 10) };
+}
+
+const expirationTimeRegex = /request\.time\s*<\s*timestamp\("([^"]+)"\)/;
+
+// Splits on literal " && " — assumes CEL string values don't contain " && ".
+// This is safe for Bytebase-generated expressions but may break on hand-crafted CEL.
+export function getConditionExpression(expression: string): string {
+ if (!expression) return "";
+ return expression
+ .split(" && ")
+ .filter((part) => !expirationTimeRegex.test(part))
+ .join(" && ");
+}
+
+export function parseExpirationTimestamp(
+ expression: string
+): number | undefined {
+ if (!expression) return undefined;
+ const match = expirationTimeRegex.exec(expression);
+ if (!match) return undefined;
+ return new Date(match[1]).getTime();
+}
+
+// Keep a local extraction function instead of importing extractDatabaseResourceName
+// from @/utils. That utility transitively pulls in store dependencies (Pinia, etc.)
+// which break vitest when this file is imported from unit tests.
+const databaseResourcePattern =
+ /(?:^|\/)instances\/(?<instanceName>[^/]+)\/databases\/(?<databaseName>[^/]+)(?:$|\/)/;
+
+export function extractDatabaseName(resource: string): string {
+ const matches = resource.match(databaseResourcePattern);
+ return matches?.groups?.databaseName ?? "";
+}
+
+export const operatorDisplayMap: Record<string, string> = {
+ "<=": "≤",
+ ">=": "≥",
+ "<": "<",
+ ">": ">",
+ "==": "=",
+ "!=": "≠",
+};
+
+// Show up to 2 items + "+N more" for the rest
+function listItems(items: string[]): string {
+ const shown = items.slice(0, 2).join(", ");
+ const rest = items.length - 2;
+ return rest > 0 ? `${shown} ${t("common.n-more", { n: rest })}` : shown;
+}
+
+export function generateGrantTitle(grant: ExemptionGrant): string {
+ const resources = grant.databaseResources ?? [];
+ const level = grant.classificationLevel;
+
+ const levelSuffix = level
+ ? `, ${t("project.masking-exemption.level")} ${operatorDisplayMap[level.operator] ?? level.operator} ${level.value}`
+ : "";
+
+ const realResources = resources.filter((r) => {
+ const dbName = extractDatabaseName(r.databaseFullName);
+ return dbName !== "";
+ });
+
+ // No specific databases
+ if (realResources.length === 0) {
+ return `${t("database.all")}${levelSuffix}`;
+ }
+
+ // Collect unique database names
+ const dbNames = [
+ ...new Set(
+ realResources.map((r) => extractDatabaseName(r.databaseFullName))
+ ),
+ ];
+
+ // Multiple databases: show first 2, no table/schema detail
+ if (dbNames.length > 1) {
+ return `${listItems(dbNames)}${levelSuffix}`;
+ }
+
+ // Single database — drill down the hierarchy.
+ // At each level: if 1 value, show it and continue deeper.
+ // If multiple values, show up to 2 + "+N more" and stop.
+ const dbName = dbNames[0];
+ const schemas = [
+ ...new Set(
+ realResources.map((r) => r.schema).filter((s): s is string => !!s)
+ ),
+ ];
+ const tables = [
+ ...new Set(
+ realResources.map((r) => r.table).filter((t): t is string => !!t)
+ ),
+ ];
+ const columns = [
+ ...new Set(
+ realResources
+ .flatMap((r) => r.columns ?? [])
+ .filter((c): c is string => !!c)
+ ),
+ ];
+
+ // No schema, no table — just database
+ if (schemas.length === 0 && tables.length === 0) {
+ return `${dbName}${levelSuffix}`;
+ }
+
+ // Multiple schemas — list and stop
+ if (schemas.length > 1) {
+ return `${dbName} (${listItems(schemas)})${levelSuffix}`;
+ }
+
+ // Single schema
+ if (schemas.length === 1) {
+ const schema = schemas[0];
+
+ // No tables — show schema keyword
+ if (tables.length === 0) {
+ return `${dbName} (${t("common.schema").toLowerCase()} ${schema})${levelSuffix}`;
+ }
+
+ // Multiple tables under one schema — colon list and stop
+ if (tables.length > 1) {
+ return `${dbName} (${schema}: ${listItems(tables)})${levelSuffix}`;
+ }
+
+ // Single table — dot notation, continue to columns
+ const table = tables[0];
+ if (columns.length === 0) {
+ return `${dbName} (${schema}.${table})${levelSuffix}`;
+ }
+ if (columns.length === 1) {
+ return `${dbName} (${schema}.${table}.${columns[0]})${levelSuffix}`;
+ }
+ return `${dbName} (${schema}.${table}: ${listItems(columns)})${levelSuffix}`;
+ }
+
+ // No schema, has tables
+ if (tables.length > 1) {
+ return `${dbName} (${listItems(tables)})${levelSuffix}`;
+ }
+
+ // No schema, single table — continue to columns
+ const table = tables[0];
+ if (columns.length === 0) {
+ return `${dbName} (${t("common.table").toLowerCase()} ${table})${levelSuffix}`;
+ }
+ if (columns.length === 1) {
+ return `${dbName} (${table}.${columns[0]})${levelSuffix}`;
+ }
+ return `${dbName} (${table}: ${listItems(columns)})${levelSuffix}`;
+}
+
+// Rewrite `resource.database == "instances/X/databases/Y"` to
+// `resource.instance_id == "X" && resource.database_name == "Y"`.
+// The expression editor uses resource.database as a combined selector,
+// but the backend masking exemption evaluator only knows individual attributes.
+export function rewriteResourceDatabase(celString: string): string {
+ return celString.replaceAll(
+ /resource\.database\s*==\s*"([^"]+)"/g,
+ (_match, fullPath: string) => {
+ const matches = fullPath.match(databaseResourcePattern);
+ const instanceName = matches?.groups?.instanceName ?? "";
+ const databaseName = matches?.groups?.databaseName ?? "";
+ return `resource.instance_id == "${instanceName}" && resource.database_name == "${databaseName}"`;
+ }
+ );
+}
+
+export function buildMemberSummary(grants: ExemptionGrant[]): {
+ databaseNames: string[];
+ neverExpires: boolean;
+ nearestExpiration: number | undefined;
+} {
+ const databaseNames = [
+ ...new Set(
+ grants.flatMap((g) =>
+ (g.databaseResources ?? []).map((r) =>
+ extractDatabaseName(r.databaseFullName)
+ )
+ )
+ ),
+ ];
+ // Grants with no databaseResources cover all databases — add empty sentinel
+ // so the member item can detect and display "All databases".
+ if (
+ grants.some((g) => !g.databaseResources || g.databaseResources.length === 0)
+ ) {
+ databaseNames.push("");
+ }
+ const expiringGrants = grants.filter((g) => g.expirationTimestamp);
+ return {
+ databaseNames,
+ neverExpires: grants.some((g) => !g.expirationTimestamp),
+ nearestExpiration:
+ expiringGrants.length > 0
+ ? Math.min(...expiringGrants.map((g) => g.expirationTimestamp!))
+ : undefined,
+ };
+}
+
+export function groupByMember(accessUsers: AccessUser[]): ExemptionMember[] {
+ // Track each member's entries and the index of their last (most recent) entry
+ const memberMap = new Map<
+ string,
+ { users: AccessUser[]; lastIndex: number }
+ >();
+ for (let i = 0; i < accessUsers.length; i++) {
+ const user = accessUsers[i];
+ const entry = memberMap.get(user.member) ?? { users: [], lastIndex: 0 };
+ entry.users.push(user);
+ entry.lastIndex = i;
+ memberMap.set(user.member, entry);
+ }
+
+ return Array.from(memberMap.entries())
+ .sort((a, b) => b[1].lastIndex - a[1].lastIndex)
+ .map(([member, { users }]) => {
+ // Each AccessUser = one grant card. No merging — each API exemption
+ // is shown as-is to avoid semantic confusion when conditions differ.
+ const grants: ExemptionGrant[] = users
+ .map((u, i) => ({
+ id: `${member}:${i}`,
+ description: u.description || "",
+ expirationTimestamp: u.expirationTimestamp,
+ rawExpression: u.rawExpression,
+ databaseResources: u.databaseResources,
+ conditionExpression: u.conditionExpression,
+ classificationLevel: parseClassificationLevel(u.conditionExpression),
+ }))
+ .reverse(); // Latest first
+
+ return {
+ type: users[0].type,
+ member,
+ grants,
+ ...buildMemberSummary(grants),
+ };
+ });
+}
diff --git a/frontend/src/components/SensitiveData/types.ts b/frontend/src/components/SensitiveData/types.ts
index edcf316014..e468e0ec0b 100644
--- a/frontend/src/components/SensitiveData/types.ts
+++ b/frontend/src/components/SensitiveData/types.ts
@@ -24,15 +24,40 @@ export interface SensitiveColumn {
maskData: MaskData;
}
-export interface AccessUser {
- type: "user" | "group";
- key: string;
- member: string;
+export interface ClassificationLevel {
+ operator: string;
+ value: number;
+}
+
+export interface ExemptionGrant {
+ id: string;
+ description: string;
expirationTimestamp?: number;
rawExpression: string;
- description: string;
databaseResources?: DatabaseResource[];
// The condition portion of the CEL expression, excluding request.time.
// Used as fallback display when databaseResources can't be parsed.
conditionExpression: string;
+ classificationLevel?: ClassificationLevel;
+ // TODO(BYT-9098): Add grantedBy (creator) and grantedAt (creation timestamp)
+ // for auditability. Requires proto change: MaskingExemptionPolicy_Exemption
+ // currently only stores members + condition. The DB policy table only has
+ // updated_at, no created_at or creator. Needs schema migration + proto update.
+}
+
+// Raw parsed entry before grouping. Inherits grant fields but omits
+// id and classificationLevel which are computed during groupByMember.
+export interface AccessUser
+ extends Omit<ExemptionGrant, "id" | "classificationLevel"> {
+ type: "user" | "group";
+ member: string;
+}
+
+export interface ExemptionMember {
+ type: "user" | "group";
+ member: string;
+ grants: ExemptionGrant[];
+ databaseNames: string[];
+ neverExpires: boolean;
+ nearestExpiration?: number;
}
diff --git a/frontend/src/components/SensitiveData/useExemptionData.ts b/frontend/src/components/SensitiveData/useExemptionData.ts
new file mode 100644
index 0000000000..ec61196210
--- /dev/null
+++ b/frontend/src/components/SensitiveData/useExemptionData.ts
@@ -0,0 +1,258 @@
+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
new file mode 100644
index 0000000000..6325f4b22f
--- /dev/null
+++ b/frontend/src/components/SensitiveData/useExemptionSearchScopeOptions.ts
@@ -0,0 +1,73 @@
+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/locales/en-US.json b/frontend/src/locales/en-US.json
index 07c9c677dd..88da54749a 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -282,7 +282,9 @@
"column": "Column",
"apply-to-database": "Apply to database",
"unlimited": "Unlimited",
- "unknown": "Unknown"
+ "unknown": "Unknown",
+ "scope": "Scope",
+ "classification-level": "Classification Level"
},
"error-page": {
"forbidden": "Forbidden",
@@ -2006,7 +2008,14 @@
"masking-exemption": {
"self": "Masking Exemptions",
"grant-exemption": "Grant Exemption",
- "revoke-exemption-title": "Remove both export and query masking exemptions for {member}?"
+ "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": "Expires in {days} day | Expires in {days} days",
+ "all-levels": "All levels",
+ "n-exemptions": "{n} exemption | {n} exemptions",
+ "level": "level"
},
"batch": {
"selected": "{count} project selected | {count} projects selected",
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index e7e9325332..6231dec66c 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -279,7 +279,9 @@
"confirm-archive": "Archive Resource?",
"confirm-delete": "Delete Resource?",
"archive-description": "Mark \"{name}\" as archived and read-only.",
- "delete-resource-description": "Once you delete \"{name}\", there is no going back. Please be certain."
+ "delete-resource-description": "Once you delete \"{name}\", there is no going back. Please be certain.",
+ "scope": "Alcance",
+ "classification-level": "Nivel de clasificación"
},
"error-page": {
"forbidden": "Prohibido",
@@ -2003,7 +2005,14 @@
"masking-exemption": {
"self": "Exenciones de Enmascaramiento",
"grant-exemption": "Conceder Exención",
- "revoke-exemption-title": "Eliminar tanto las exenciones de exportación como de consulta de enmascaramiento para {member}?"
+ "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": "Expira en {days} día | Expira en {days} días",
+ "all-levels": "Todos los niveles",
+ "n-exemptions": "{n} exención | {n} exenciones",
+ "level": "nivel"
},
"batch": {
"selected": "{count} proyecto seleccionado | {count} proyectos seleccionados",
diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.json
index c71cc16ea8..58aeaba5e9 100644
--- a/frontend/src/locales/ja-JP.json
+++ b/frontend/src/locales/ja-JP.json
@@ -279,7 +279,9 @@
"confirm-archive": "Archive Resource?",
"confirm-delete": "Delete Resource?",
"archive-description": "Mark \"{name}\" as archived and read-only.",
- "delete-resource-description": "Once you delete \"{name}\", there is no going back. Please be certain."
+ "delete-resource-description": "Once you delete \"{name}\", there is no going back. Please be certain.",
+ "scope": "スコープ",
+ "classification-level": "分類レベル"
},
"error-page": {
"forbidden": "アクセス禁止",
@@ -2003,7 +2005,14 @@
"masking-exemption": {
"self": "マスキング免除",
"grant-exemption": "免除を付与",
- "revoke-exemption-title": "{member} のエクスポートおよびクエリのマスキング免除を両方削除しますか?"
+ "revoke-exemption-title": "{member} のマスキング免除を削除しますか?",
+ "no-reason": "理由が提供されていません",
+ "no-exemptions": "マスキング免除はまだ付与されていません",
+ "expires-today": "本日期限切れ",
+ "expires-in-days": "{days} 日後に期限切れ",
+ "all-levels": "全レベル",
+ "n-exemptions": "{n} 件の免除",
+ "level": "レベル"
},
"batch": {
"selected": "{count} 件のプロジェクトが選択されました | {count} 件のプロジェクトが選択されました",
diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.json
index 4e89d07cfc..cc22d8f867 100644
--- a/frontend/src/locales/vi-VN.json
+++ b/frontend/src/locales/vi-VN.json
@@ -279,7 +279,9 @@
"confirm-archive": "Archive Resource?",
"confirm-delete": "Delete Resource?",
"archive-description": "Mark \"{name}\" as archived and read-only.",
- "delete-resource-description": "Once you delete \"{name}\", there is no going back. Please be certain."
+ "delete-resource-description": "Once you delete \"{name}\", there is no going back. Please be certain.",
+ "scope": "Phạm vi",
+ "classification-level": "Cấp phân loại"
},
"error-page": {
"forbidden": "Bị cấm",
@@ -2003,7 +2005,14 @@
"masking-exemption": {
"self": "Miễn trừ Che giấu",
"grant-exemption": "Cấp Miễn trừ",
- "revoke-exemption-title": "Xóa cả miễn trừ che giấu xuất và truy vấn cho {member}?"
+ "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": "Hết hạn sau {days} ngày",
+ "all-levels": "Tất cả các cấp",
+ "n-exemptions": "{n} miễn trừ",
+ "level": "cấp"
},
"batch": {
"selected": "{count} dự án đã chọn | {count} dự án đã chọn",
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index 884d9afc23..314dd4df82 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -279,7 +279,9 @@
"confirm-archive": "确定归档资源?",
"confirm-delete": "确定删除资源?",
"archive-description": "将「{name}」标记为已归档且只读。",
- "delete-resource-description": "删除「{name}」后将无法恢复,请确认。"
+ "delete-resource-description": "删除「{name}」后将无法恢复,请确认。",
+ "scope": "范围",
+ "classification-level": "分类等级"
},
"error-page": {
"forbidden": "禁止访问",
@@ -2003,7 +2005,14 @@
"masking-exemption": {
"self": "脱敏豁免",
"grant-exemption": "授予豁免",
- "revoke-exemption-title": "是否撤销 {member} 的导出和查询脱敏?"
+ "revoke-exemption-title": "是否撤销 {member} 的脱敏豁免?",
+ "no-reason": "未提供原因",
+ "no-exemptions": "尚未授予脱敏豁免",
+ "expires-today": "今天到期",
+ "expires-in-days": "{days} 天后到期",
+ "all-levels": "所有等级",
+ "n-exemptions": "{n} 项豁免",
+ "level": "等级"
},
"batch": {
"selected": "已选择 {count} 个项目 | 已选择 {count} 个项目",
diff --git a/frontend/src/plugins/cel/types/operator.ts b/frontend/src/plugins/cel/types/operator.ts
index 75c84b381e..0cc3935945 100644
--- a/frontend/src/plugins/cel/types/operator.ts
+++ b/frontend/src/plugins/cel/types/operator.ts
@@ -75,6 +75,28 @@ export const isStringOperator = (op: Operator): op is StringOperator => {
return StringOperatorList.includes(op as StringOperator);
};
+// Display labels for operators that differ from their source form.
+const OPERATOR_DISPLAY: Record<string, string> = {
+ "<=": "≤",
+ ">=": "≥",
+ "==": "=",
+ "!=": "≠",
+ "@not_in": "not in",
+ "@not_contains": "not contains",
+};
+
+// Returns a human-readable label for any operator form:
+// plain ("<="), CEL AST ("_<=_"), or prefixed ("@not_in").
+export function operatorDisplayLabel(op: string): string {
+ if (op in OPERATOR_DISPLAY) return OPERATOR_DISPLAY[op];
+ // CEL AST operators like "_<=_" — strip surrounding underscores.
+ if (op.startsWith("_")) {
+ const plain = op.replace(/^_|_$/g, "");
+ return OPERATOR_DISPLAY[plain] ?? plain;
+ }
+ return op;
+}
+
/// Define supported operators for each factor
const OperatorList: Record<Factor, Operator[]> = {
[CEL_ATTRIBUTE_STATEMENT_AFFECTED_ROWS]: uniq([
diff --git a/frontend/src/react/components/ExprEditor.tsx b/frontend/src/react/components/ExprEditor.tsx
index a98b0cf3e6..57394d3af3 100644
--- a/frontend/src/react/components/ExprEditor.tsx
+++ b/frontend/src/react/components/ExprEditor.tsx
@@ -36,6 +36,7 @@ import {
isStringOperator,
isTimestampFactor,
LogicalOperatorList,
+ operatorDisplayLabel,
} from "@/plugins/cel";
import { EnvironmentLabel } from "@/react/components/EnvironmentLabel";
import { Input } from "@/react/components/ui/input";
@@ -782,19 +783,8 @@ function FactorSelect({
// OperatorSelect
// ============================================================
-const OPERATOR_DICT: Record<string, string> = {
- "_==_": "==",
- "_!=_": "!=",
- "_<_": "<",
- "_<=_": "≤",
- "_>=_": "≥",
- "_>_": ">",
- "@not_in": "not in",
- "@not_contains": "not contains",
-};
-
function operatorLabel(op: string): string {
- return OPERATOR_DICT[op] ?? op.replace(/^@/, "");
+ return operatorDisplayLabel(op);
}
function OperatorSelect({
diff --git a/frontend/src/views/project/ProjectMaskingExemption.vue b/frontend/src/views/project/ProjectMaskingExemption.vue
index 5afa6a3a03..2b0f25cf6d 100644
--- a/frontend/src/views/project/ProjectMaskingExemption.vue
+++ b/frontend/src/views/project/ProjectMaskingExemption.vue
@@ -1,25 +1,14 @@
<template>
- <div class="py-4 flex flex-col">
- <div class="px-4 pb-2">
- <div
- class="flex flex-row justify-between items-center gap-x-2"
- >
- <DatabaseSelect
- class="hidden sm:block"
- style="max-width: max-content"
- :placeholder="$t('database.select')"
- :project-name="project.name"
- :show-instance="false"
- v-model:value="state.selectedDatabaseName"
- />
-
- <div class="flex-1 flex flex-row items-center justify-end gap-x-2">
- <SearchBox
- ref="searchField"
- v-model:value="state.searchText"
- style="max-width: 100%"
- :placeholder="$t('settings.members.search-member')"
+ <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"
@@ -27,23 +16,13 @@
'bb.policies.createMaskingExemptionPolicy',
'bb.policies.updateMaskingExemptionPolicy',
'bb.databases.list',
- 'bb.databaseCatalogs.get'
+ 'bb.databaseCatalogs.get',
]"
>
<NButton
type="primary"
:disabled="slotProps.disabled"
- @click="
- () => {
- if (!hasSensitiveDataFeature) {
- state.showFeatureModal = true;
- return;
- }
- router.push({
- name: PROJECT_V1_ROUTE_MASKING_EXEMPTION_CREATE,
- });
- }
- "
+ @click="handleGrantClick"
>
<template #icon>
<ShieldCheckIcon class="w-4" />
@@ -56,58 +35,116 @@
</NButton>
</PermissionGuardWrapper>
</div>
+ <ExemptionPresetTabs
+ :params="searchParams"
+ @update:params="searchParams = $event"
+ />
</div>
- </div>
- <MaskingExceptionUserTable
- size="medium"
- :disabled="!hasPermission"
- :project="project"
- :show-database-column="true"
- :filter-access-user="filterAccessUser"
- />
+
+ <!-- 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="state.showFeatureModal"
+ :open="showFeatureModal"
:feature="PlanFeature.FEATURE_DATA_MASKING"
- @cancel="state.showFeatureModal = false"
+ @cancel="showFeatureModal = false"
/>
</template>
-<script lang="tsx" setup>
+<script lang="ts" setup>
import { ShieldCheckIcon } from "lucide-vue-next";
-import { NButton } from "naive-ui";
-import { computed, reactive } from "vue";
+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 MaskingExceptionUserTable from "@/components/SensitiveData/MaskingExceptionUserTable.vue";
-import { type AccessUser } from "@/components/SensitiveData/types";
-import { DatabaseSelect, SearchBox } from "@/components/v2";
+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 { hasProjectPermissionV2 } from "@/utils";
-
-interface LocalState {
- searchText: string;
- showFeatureModal: boolean;
- selectedDatabaseName?: string;
-}
+import {
+ getValueFromSearchParams,
+ hasProjectPermissionV2,
+ type SearchParams,
+} from "@/utils";
const props = defineProps<{
projectId: string;
}>();
-const state = reactive<LocalState>({
- searchText: "",
- showFeatureModal: false,
-});
-const router = useRouter();
+const { t } = useI18n(); // NOSONAR
+const router = useRouter(); // NOSONAR
+const $dialog = useDialog(); // NOSONAR
-const { project } = useProjectByName(
- computed(() => `${projectNamePrefix}${props.projectId}`)
+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(() =>
@@ -117,26 +154,119 @@ const hasPermission = computed(() =>
)
);
-const hasSensitiveDataFeature = computed(() => {
- return hasFeature(PlanFeature.FEATURE_DATA_MASKING);
+const hasSensitiveDataFeature = computed(() =>
+ hasFeature(PlanFeature.FEATURE_DATA_MASKING)
+);
+
+const searchParams = ref<SearchParams>({
+ query: "",
+ scopes: [{ id: "status", value: "active" }],
});
-const filterAccessUser = (user: AccessUser): boolean => {
- if (
- state.searchText.trim() &&
- !user.key.toLowerCase().includes(state.searchText.trim())
- ) {
- return false;
+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));
}
- if (state.selectedDatabaseName) {
- if (!user.databaseResources) {
- return true;
- }
- return user.databaseResources.some(
- (r) => r.databaseFullName === state.selectedDatabaseName
+
+ const memberScope = getValueFromSearchParams(searchParams.value, "member");
+ if (memberScope) {
+ result = result.filter((m) =>
+ m.member.toLowerCase().includes(memberScope.toLowerCase())
);
}
- return true;
+ // 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>