Skip to content

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

chore: implement project access user list page (#14195)

ecmadao3a52d41ee923
diff --git a/frontend/src/components/ColumnDataTable/MaskingLevelCell.vue b/frontend/src/components/ColumnDataTable/MaskingLevelCell.vue
index e0cb4bddd1..577eb290c0 100644
--- a/frontend/src/components/ColumnDataTable/MaskingLevelCell.vue
+++ b/frontend/src/components/ColumnDataTable/MaskingLevelCell.vue
@@ -56,7 +56,6 @@
<SensitiveColumnDrawer
v-if="state.showSensitiveDataDrawer"
- :show="true"
:column="{
maskData: columnMasking,
database: props.database,
diff --git a/frontend/src/components/QuickActionPanel.vue b/frontend/src/components/QuickActionPanel.vue
index 3e4025b80c..552863a7af 100644
--- a/frontend/src/components/QuickActionPanel.vue
+++ b/frontend/src/components/QuickActionPanel.vue
@@ -78,6 +78,15 @@
"
@close="state.quickActionType = undefined"
/>
+ <GrantAccessDrawer
+ v-if="
+ project &&
+ state.quickActionType === 'quickaction.bb.database.masking-access'
+ "
+ :column-list="[]"
+ :project-name="project.name"
+ @close="state.quickActionType = undefined"
+ />
</template>
<FeatureModal
@@ -112,6 +121,7 @@ import {
Buttons as InstanceFormButtons,
} from "@/components/InstanceForm/";
import ProjectCreatePanel from "@/components/Project/ProjectCreatePanel.vue";
+import GrantAccessDrawer from "@/components/SensitiveData/GrantAccessDrawer.vue";
import { TransferDatabaseForm } from "@/components/TransferDatabaseForm";
import { Drawer, DrawerContent } from "@/components/v2";
import { PROJECT_V1_ROUTE_DATABASE_GROUP_DETAIL } from "@/router/dashboard/projectV1";
diff --git a/frontend/src/components/SensitiveData/MaskingExceptionUserTable.vue b/frontend/src/components/SensitiveData/MaskingExceptionUserTable.vue
index 71234e1d2e..8ee08aed33 100644
--- a/frontend/src/components/SensitiveData/MaskingExceptionUserTable.vue
+++ b/frontend/src/components/SensitiveData/MaskingExceptionUserTable.vue
@@ -2,7 +2,7 @@
<NDataTable
:size="size"
:columns="accessTableColumns"
- :data="accessList"
+ :data="state.accessList"
:row-key="(row: AccessUser) => row.key"
:bordered="true"
:striped="true"
@@ -12,50 +12,259 @@
</template>
<script lang="tsx" setup>
-import { cloneDeep } from "lodash-es";
+import { orderBy } from "lodash-es";
import { TrashIcon } from "lucide-vue-next";
import type { DataTableColumn } from "naive-ui";
-import { NCheckbox, NDatePicker, NPopconfirm, NDataTable } from "naive-ui";
-import { computed } from "vue";
+import { NCheckbox, NDatePicker, NDataTable, useDialog } from "naive-ui";
+import { computed, watch, reactive, h } from "vue";
+import type { VNodeChild } from "vue";
import { useI18n } from "vue-i18n";
import { RouterLink } from "vue-router";
+import { useRouter } from "vue-router";
import GroupNameCell from "@/components/User/Settings/UserDataTableByGroup/cells/GroupNameCell.vue";
import { MiniActionButton } from "@/components/v2";
+import { DatabaseV1Name, InstanceV1Name } from "@/components/v2";
import { WORKSPACE_ROUTE_USER_PROFILE } from "@/router/dashboard/workspaceRoutes";
-import { MaskingLevel } from "@/types/proto/v1/common";
+import {
+ usePolicyV1Store,
+ usePolicyByParentAndType,
+ useUserStore,
+ useGroupStore,
+ useDatabaseV1Store,
+ pushNotification,
+ extractGroupEmail,
+} from "@/store";
+import {
+ getUserEmailInBinding,
+ getGroupEmailInBinding,
+ groupBindingPrefix,
+} from "@/types";
+import { Expr } from "@/types/proto/google/type/expr";
+import { MaskingLevel, maskingLevelToJSON } from "@/types/proto/v1/common";
import { MaskingExceptionPolicy_MaskingException_Action } from "@/types/proto/v1/org_policy_service";
-import { hasWorkspacePermissionV2 } from "@/utils";
+import type {
+ Policy,
+ MaskingExceptionPolicy_MaskingException,
+} from "@/types/proto/v1/org_policy_service";
+import { PolicyType } from "@/types/proto/v1/org_policy_service";
+import { autoDatabaseRoute, hasWorkspacePermissionV2 } from "@/utils";
+import { convertFromCELString } from "@/utils/issue/cel";
import UserAvatar from "../User/UserAvatar.vue";
import MaskingLevelDropdown from "./components/MaskingLevelDropdown.vue";
import { type AccessUser } from "./types";
+interface LocalState {
+ processing: boolean;
+ accessList: AccessUser[];
+}
+
const props = defineProps<{
size: "small" | "medium";
- accessList: AccessUser[];
disabled: boolean;
+ // project full name
+ project: string;
showDatabaseColumn: boolean;
+ filterException: (
+ exception: MaskingExceptionPolicy_MaskingException
+ ) => boolean;
}>();
-const emit = defineEmits<{
- (event: "update:access", index: number, access: AccessUser): void;
- (event: "remove:access", index: number): void;
-}>();
-
+const state = reactive<LocalState>({
+ processing: false,
+ accessList: [],
+});
const { t } = useI18n();
+const router = useRouter();
+const userStore = useUserStore();
+const groupStore = useGroupStore();
+const databaseStore = useDatabaseV1Store();
+const policyStore = usePolicyV1Store();
+const $dialog = useDialog();
+
const hasPermission = computed(() => {
return hasWorkspacePermissionV2("bb.policies.update");
});
-const getDatabaseAccessResource = (expr: string) => {
- const expressions = expr
- .split(" && ")
- .filter((expr) => !expr.startsWith("request.time"));
- if (expressions.length === 0) {
- expressions.push("all databases");
+const policy = usePolicyByParentAndType(
+ computed(() => ({
+ parentPath: props.project,
+ policyType: PolicyType.MASKING_EXCEPTION,
+ }))
+);
+
+const getDatabaseAccessResource = (access: AccessUser): VNodeChild => {
+ if (!access.databaseResource) {
+ return <div class="textinfo">{t("database.all")}</div>;
}
- return expressions;
+ // const databaseFullName
+ const database = databaseStore.getDatabaseByName(
+ access.databaseResource.databaseName
+ );
+
+ return (
+ <div class="space-y-1">
+ <div class="flex items-center gap-x-1 text-sm textinfo">
+ <span>{`${t("common.instance")}:`}</span>
+ <InstanceV1Name instance={database.instanceResource} />
+ </div>
+ <div class="flex items-center gap-x-1 text-sm textinfo">
+ <span>{`${t("common.database")}:`}</span>
+ <div
+ class="normal-link hover:underline"
+ onClick={() => {
+ const query: Record<string, string> = {};
+ if (access.databaseResource?.schema) {
+ query.schema = access.databaseResource.schema;
+ }
+ if (access.databaseResource?.table) {
+ query.table = access.databaseResource.table;
+ }
+ router.push({
+ ...autoDatabaseRoute(router, database),
+ query,
+ });
+ }}
+ >
+ <DatabaseV1Name database={database} link={false} />
+ </div>
+ </div>
+ {access.databaseResource.schema && (
+ <div class="text-sm textinfo">{`${t("common.schema")}: ${access.databaseResource.schema}`}</div>
+ )}
+ {access.databaseResource.table && (
+ <div class="text-sm textinfo">{`${t("common.table")}: ${access.databaseResource.table}`}</div>
+ )}
+ {access.databaseResource.column && (
+ <div class="text-sm textinfo">{`${t("database.column")}: ${access.databaseResource.column}`}</div>
+ )}
+ </div>
+ );
};
+const expirationTimeRegex = /request.time < timestamp\("(.+)?"\)/;
+
+const getAccessUsers = async (
+ exception: MaskingExceptionPolicy_MaskingException
+): Promise<AccessUser | undefined> => {
+ let expirationTimestamp: number | undefined;
+ const expression = exception.condition?.expression ?? "";
+ const matches = expirationTimeRegex.exec(expression);
+ if (matches) {
+ expirationTimestamp = new Date(matches[1]).getTime();
+ }
+ const conditionExpression = await convertFromCELString(expression);
+
+ const access: AccessUser = {
+ type: "user",
+ key: exception.member,
+ maskingLevel: exception.maskingLevel,
+ expirationTimestamp,
+ supportActions: new Set([exception.action]),
+ rawExpression: expression,
+ databaseResource: conditionExpression.databaseResources
+ ? conditionExpression.databaseResources[0]
+ : undefined,
+ };
+
+ if (exception.member.startsWith(groupBindingPrefix)) {
+ access.type = "group";
+ access.group = groupStore.getGroupByIdentifier(exception.member);
+ } else {
+ access.type = "user";
+ access.user = userStore.getUserByIdentifier(exception.member);
+ }
+
+ if (!access.group && !access.user) {
+ return;
+ }
+
+ return access;
+};
+
+const getExceptionIdentifier = (
+ exception: MaskingExceptionPolicy_MaskingException
+): string => {
+ const expression = exception.condition?.expression ?? "";
+ const res: string[] = [
+ `level:"${maskingLevelToJSON(exception.maskingLevel)}"`,
+ expression,
+ ];
+ return res.join(" && ");
+};
+
+const getMemberBinding = (access: AccessUser): string => {
+ if (access.type === "user") {
+ return getUserEmailInBinding(access.user!.email);
+ }
+ const email = extractGroupEmail(access.group!.name);
+ return getGroupEmailInBinding(email);
+};
+
+const updateAccessUserList = async (policy: Policy | undefined) => {
+ if (!policy || !policy.maskingExceptionPolicy) {
+ return [];
+ }
+
+ // Exec data merge, we will merge data with same expiration time and level.
+ // For example, the exception list and merge exec should be:
+ // - 1. user1, action:export, level:FULL, expires at 2023-09-03
+ // - 2. user1, action:export, level:FULL, expires at 2023-09-04
+ // - 3. user1, action:export, level:PARTIAL, expires at 2023-09-04
+ // - 4. user1, action:query, level:PARTIAL, expires at 2023-09-04
+ // - 5. user1, action:query, level:FULL, expires at 2023-09-03
+ // After the merge we should get:
+ // - 1 & 5 is merged: user1, action:export+action, level:FULL, expires at 2023-09-03
+ // - 2 cannot merge: user1, action:export, level:FULL, expires at 2023-09-04
+ // - 3 & 4 is merged: user1, action:export+action, level:PARTIAL, expires at 2023-09-04
+ const memberMap = new Map<string, AccessUser>();
+ for (const exception of policy.maskingExceptionPolicy.maskingExceptions) {
+ if (!props.filterException(exception)) {
+ continue;
+ }
+ const identifier = getExceptionIdentifier(exception);
+ const item = await getAccessUsers(exception);
+ if (!item) {
+ continue;
+ }
+ const id = `${getMemberBinding(item)}:${identifier}`;
+ item.key = id;
+ const target = memberMap.get(id) ?? item;
+ if (memberMap.has(id)) {
+ for (const action of item.supportActions) {
+ target.supportActions.add(action);
+ }
+ }
+ memberMap.set(id, target);
+ }
+
+ state.accessList = orderBy(
+ [...memberMap.values()],
+ [
+ (access) => (access.type === "user" ? 1 : 0),
+ (access) => {
+ if (access.group) {
+ return access.group.name;
+ } else if (access.user) {
+ return access.user.name;
+ }
+ return "";
+ },
+ ],
+ ["desc", "desc"]
+ );
+};
+
+watch(
+ () => policy.value,
+ async (policy) => {
+ await updateAccessUserList(policy);
+ },
+ {
+ immediate: true,
+ deep: true,
+ }
+);
+
const accessTableColumns = computed(
(): DataTableColumn<AccessUser & { hide?: boolean }>[] => {
return [
@@ -64,15 +273,7 @@ const accessTableColumns = computed(
expandable: (_: AccessUser) => true,
hide: props.showDatabaseColumn,
renderExpand: (item: AccessUser) => {
- const expressions = getDatabaseAccessResource(item.rawExpression);
-
- return (
- <ul class="list-disc pl-6 textinfolabel">
- {expressions.map((expression, i) => (
- <li key={`${item.key}.${i}`}>{expression}</li>
- ))}
- </ul>
- );
+ return getDatabaseAccessResource(item);
},
},
{
@@ -108,17 +309,10 @@ const accessTableColumns = computed(
{
key: "resource",
title: t("common.resource"),
+ resizable: true,
hide: !props.showDatabaseColumn,
render: (item: AccessUser) => {
- const expressions = getDatabaseAccessResource(item.rawExpression);
-
- return (
- <ul class="list-disc">
- {expressions.map((expression, i) => (
- <li key={`${item.key}.${i}`}>{expression}</li>
- ))}
- </ul>
- );
+ return getDatabaseAccessResource(item);
},
},
{
@@ -132,13 +326,19 @@ const accessTableColumns = computed(
MaskingExceptionPolicy_MaskingException_Action.EXPORT
)}
disabled={!hasPermission.value || props.disabled}
- onUpdateChecked={(e) =>
- onAccessControlUpdate(row, (item) =>
- toggleAction(
- item,
- MaskingExceptionPolicy_MaskingException_Action.EXPORT,
- e
- )
+ onUpdateChecked={() =>
+ onAccessControlUpdate(
+ row,
+ (item) =>
+ toggleAction(
+ item,
+ MaskingExceptionPolicy_MaskingException_Action.EXPORT
+ ),
+ (item) =>
+ toggleAction(
+ item,
+ MaskingExceptionPolicy_MaskingException_Action.EXPORT
+ )
)
}
/>
@@ -156,13 +356,19 @@ const accessTableColumns = computed(
MaskingExceptionPolicy_MaskingException_Action.QUERY
)}
disabled={!hasPermission.value || props.disabled}
- onUpdate:checked={(e) =>
- onAccessControlUpdate(row, (item) =>
- toggleAction(
- item,
- MaskingExceptionPolicy_MaskingException_Action.QUERY,
- e
- )
+ onUpdate:checked={() =>
+ onAccessControlUpdate(
+ row,
+ (item) =>
+ toggleAction(
+ item,
+ MaskingExceptionPolicy_MaskingException_Action.QUERY
+ ),
+ (item) =>
+ toggleAction(
+ item,
+ MaskingExceptionPolicy_MaskingException_Action.QUERY
+ )
)
}
/>
@@ -213,29 +419,16 @@ const accessTableColumns = computed(
hide: !hasPermission.value,
width: "4rem",
render: (_: AccessUser, row: number) => {
- return (
- <NPopconfirm onPositiveClick={() => emit("remove:access", row)}>
- {{
- trigger: () => {
- return (
- <MiniActionButton
- disabled={!hasPermission.value || props.disabled}
- >
- {{
- default: () => <TrashIcon class="w-4 h-4" />,
- }}
- </MiniActionButton>
- );
- },
- default: () => (
- <div class="whitespace-nowrap">
- {t(
- "settings.sensitive-data.column-detail.remove-user-permission"
- )}
- </div>
- ),
- }}
- </NPopconfirm>
+ return h(
+ MiniActionButton,
+ {
+ onClick: () => {
+ revokeAccessAlert(row);
+ },
+ },
+ {
+ default: () => h(TrashIcon, { class: "w-4 h-4" }),
+ }
);
},
},
@@ -245,25 +438,133 @@ const accessTableColumns = computed(
const toggleAction = (
item: AccessUser,
- action: MaskingExceptionPolicy_MaskingException_Action,
- checked: boolean
+ action: MaskingExceptionPolicy_MaskingException_Action
) => {
- if (checked) {
- item.supportActions.add(action);
- } else {
+ if (item.supportActions.has(action)) {
item.supportActions.delete(action);
+ } else {
+ item.supportActions.add(action);
}
};
+const revokeAccessAlert = (
+ index: number,
+ revert: (item: AccessUser) => void = () => {}
+) => {
+ const item = state.accessList[index];
+ $dialog.warning({
+ title: t("common.warning"),
+ content: () => {
+ return (
+ <div class="space-y-3">
+ <div class="textlabel !text-base">
+ {t("project.masking-access.revoke-access-title", {
+ member: getMemberBinding(item),
+ })}
+ </div>
+ {getDatabaseAccessResource(item)}
+ </div>
+ );
+ },
+ style: "z-index: 100000",
+ negativeText: t("common.cancel"),
+ positiveText: t("common.confirm"),
+ closeOnEsc: false,
+ maskClosable: false,
+ onClose: () => revert(item),
+ onPositiveClick: async () => {
+ await onRemove(index);
+ },
+ onNegativeClick: () => revert(item),
+ });
+};
+
+const onRemove = async (index: number) => {
+ state.accessList.splice(index, 1);
+ await onSubmit();
+};
+
const onAccessControlUpdate = async (
index: number,
- callback: (item: AccessUser) => void
+ callback: (item: AccessUser) => void,
+ revert: (item: AccessUser) => void = () => {}
) => {
- const item = cloneDeep(props.accessList[index]);
+ const item = state.accessList[index];
if (!item) {
return;
}
callback(item);
- emit("update:access", index, item);
+ if (item.supportActions.size === 0) {
+ revokeAccessAlert(index, revert);
+ } else {
+ await onSubmit();
+ }
+};
+
+const onSubmit = async () => {
+ 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,
+ policyType: PolicyType.MASKING_EXCEPTION,
+ });
+ if (!policy) {
+ return;
+ }
+
+ const unChangedExceptions = (
+ policy.maskingExceptionPolicy?.maskingExceptions ?? []
+ ).filter((exception) => !props.filterException(exception));
+
+ for (const accessUser of state.accessList) {
+ const expressions = accessUser.rawExpression.split(" && ");
+ 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()}")`
+ );
+ }
+ for (const action of accessUser.supportActions) {
+ unChangedExceptions.push({
+ maskingLevel: accessUser.maskingLevel,
+ action,
+ member: getMemberBinding(accessUser),
+ condition: Expr.fromPartial({
+ expression: expressions.join(" && "),
+ }),
+ });
+ }
+ }
+
+ policy.maskingExceptionPolicy = {
+ ...(policy.maskingExceptionPolicy ?? {}),
+ maskingExceptions: unChangedExceptions,
+ };
+ await policyStore.updatePolicy(["payload"], policy);
};
</script>
diff --git a/frontend/src/components/SensitiveData/SensitiveColumnDrawer.vue b/frontend/src/components/SensitiveData/SensitiveColumnDrawer.vue
index 4b4fa52249..58ed1d041d 100644
--- a/frontend/src/components/SensitiveData/SensitiveColumnDrawer.vue
+++ b/frontend/src/components/SensitiveData/SensitiveColumnDrawer.vue
@@ -1,5 +1,5 @@
<template>
- <Drawer :show="show" @close="$emit('dismiss')">
+ <Drawer :show="true" @close="$emit('dismiss')">
<DrawerContent
:title="
$t('settings.sensitive-data.column-detail.masking-setting-for-column', {
@@ -126,11 +126,12 @@
</div>
<MaskingExceptionUserTable
size="small"
- :access-list="accessUserList"
+ :project="column.database.project"
:disabled="state.processing"
:show-database-column="false"
- @remove:access="onRemove"
- @update:access="onAccessControlUpdate"
+ :filter-exception="
+ (exception) => isCurrentColumnException(exception, column)
+ "
/>
</div>
</div>
@@ -157,35 +158,20 @@
<script lang="tsx" setup>
import { computedAsync } from "@vueuse/core";
-import { orderBy } from "lodash-es";
import type { SelectOption } from "naive-ui";
import { NSelect, NButton } from "naive-ui";
-import { computed, reactive, watch, ref } from "vue";
+import { computed, reactive, onMounted } from "vue";
import { useI18n } from "vue-i18n";
import { useSemanticType } from "@/components/SensitiveData/useSemanticType";
import { Drawer, DrawerContent } from "@/components/v2";
import {
useSettingV1Store,
usePolicyV1Store,
- usePolicyByParentAndType,
- useUserStore,
- useGroupStore,
pushNotification,
useDBSchemaV1Store,
- extractGroupEmail,
} from "@/store";
-import {
- getUserEmailInBinding,
- getGroupEmailInBinding,
- groupBindingPrefix,
-} from "@/types";
-import { Expr } from "@/types/proto/google/type/expr";
-import { MaskingLevel, maskingLevelToJSON } from "@/types/proto/v1/common";
-import type {
- Policy,
- MaskData,
- MaskingExceptionPolicy_MaskingException,
-} from "@/types/proto/v1/org_policy_service";
+import { MaskingLevel } from "@/types/proto/v1/common";
+import type { Policy, MaskData } from "@/types/proto/v1/org_policy_service";
import {
PolicyType,
PolicyResourceType,
@@ -194,11 +180,10 @@ import { hasWorkspacePermissionV2 } from "@/utils";
import GrantAccessDrawer from "./GrantAccessDrawer.vue";
import MaskingExceptionUserTable from "./MaskingExceptionUserTable.vue";
import MaskingLevelRadioGroup from "./components/MaskingLevelRadioGroup.vue";
-import type { SensitiveColumn, AccessUser } from "./types";
+import type { SensitiveColumn } from "./types";
import { getMaskDataIdentifier, isCurrentColumnException } from "./utils";
interface LocalState {
- dirty: boolean;
processing: boolean;
maskingLevel: MaskingLevel;
showGrantAccessDrawer: boolean;
@@ -207,14 +192,12 @@ interface LocalState {
}
const props = defineProps<{
- show: boolean;
column: SensitiveColumn;
}>();
defineEmits(["dismiss"]);
const state = reactive<LocalState>({
- dirty: false,
processing: false,
maskingLevel: props.column.maskData.maskingLevel,
fullMaskingAlgorithmId: props.column.maskData.fullMaskingAlgorithmId,
@@ -230,9 +213,6 @@ const MASKING_LEVELS = [
];
const { t } = useI18n();
-const userStore = useUserStore();
-const groupStore = useGroupStore();
-const accessUserList = ref<AccessUser[]>([]);
const policyStore = usePolicyV1Store();
const dbSchemaStore = useDBSchemaV1Store();
const settingStore = useSettingV1Store();
@@ -250,157 +230,16 @@ const columnDefaultMaskingAlgorithm = computed(() => {
return t("settings.sensitive-data.algorithms.default");
});
-const policy = usePolicyByParentAndType(
- computed(() => ({
- parentPath: props.column.database.project,
- policyType: PolicyType.MASKING_EXCEPTION,
- }))
-);
-
const hasPermission = computed(() => {
return hasWorkspacePermissionV2("bb.policies.update");
});
-const expirationTimeRegex = /request.time < timestamp\("(.+)?"\)/;
-
-const getAccessUsers = (
- exception: MaskingExceptionPolicy_MaskingException
-): AccessUser | undefined => {
- let expirationTimestamp: number | undefined;
- const expression = exception.condition?.expression ?? "";
- const matches = expirationTimeRegex.exec(expression);
- if (matches) {
- expirationTimestamp = new Date(matches[1]).getTime();
- }
-
- const access: AccessUser = {
- type: "user",
- key: exception.member,
- maskingLevel: exception.maskingLevel,
- expirationTimestamp,
- supportActions: new Set([exception.action]),
- rawExpression: expression,
- };
-
- if (exception.member.startsWith(groupBindingPrefix)) {
- access.type = "group";
- access.group = groupStore.getGroupByIdentifier(exception.member);
- } else {
- access.type = "user";
- access.user = userStore.getUserByIdentifier(exception.member);
- }
-
- if (!access.group && !access.user) {
- return;
- }
-
- return access;
-};
-
-const getMemberBinding = (access: AccessUser): string => {
- if (access.type === "user") {
- return getUserEmailInBinding(access.user!.email);
- }
- const email = extractGroupEmail(access.group!.name);
- return getGroupEmailInBinding(email);
-};
-
-const getExceptionIdentifier = (
- exception: MaskingExceptionPolicy_MaskingException
-): string => {
- const expression = exception.condition?.expression ?? "";
- const res: string[] = [
- `level:"${maskingLevelToJSON(exception.maskingLevel)}"`,
- expression,
- ];
- return res.join(" && ");
-};
-
-const updateAccessUserList = (policy: Policy | undefined) => {
- if (!policy || !policy.maskingExceptionPolicy) {
- return [];
- }
-
- // Exec data merge, we will merge data with same expiration time and level.
- // For example, the exception list and merge exec should be:
- // - 1. user1, action:export, level:FULL, expires at 2023-09-03
- // - 2. user1, action:export, level:FULL, expires at 2023-09-04
- // - 3. user1, action:export, level:PARTIAL, expires at 2023-09-04
- // - 4. user1, action:query, level:PARTIAL, expires at 2023-09-04
- // - 5. user1, action:query, level:FULL, expires at 2023-09-03
- // After the merge we should get:
- // - 1 & 5 is merged: user1, action:export+action, level:FULL, expires at 2023-09-03
- // - 2 cannot merge: user1, action:export, level:FULL, expires at 2023-09-04
- // - 3 & 4 is merged: user1, action:export+action, level:PARTIAL, expires at 2023-09-04
- const memberMap = new Map<string, AccessUser>();
- for (const exception of policy.maskingExceptionPolicy.maskingExceptions) {
- if (!isCurrentColumnException(exception, props.column)) {
- continue;
- }
- const identifier = getExceptionIdentifier(exception);
- const item = getAccessUsers(exception);
- if (!item) {
- continue;
- }
- const id = `${getMemberBinding(item)}:${identifier}`;
- item.key = id;
- const target = memberMap.get(id) ?? item;
- if (memberMap.has(id)) {
- for (const action of item.supportActions) {
- target.supportActions.add(action);
- }
- }
- memberMap.set(id, target);
- }
-
- accessUserList.value = orderBy(
- [...memberMap.values()],
- [
- (access) => (access.type === "user" ? 1 : 0),
- (access) => {
- if (access.group) {
- return access.group.name;
- } else if (access.user) {
- return access.user.name;
- }
- return "";
- },
- ],
- ["desc", "desc"]
- );
-};
-
-watch(
- () => [props.show, policy.value],
- () => {
- if (props.show) {
- state.maskingLevel = props.column.maskData.maskingLevel;
- state.fullMaskingAlgorithmId =
- props.column.maskData.fullMaskingAlgorithmId;
- state.partialMaskingAlgorithmId =
- props.column.maskData.partialMaskingAlgorithmId;
- }
- if (props.show && policy.value) {
- updateAccessUserList(policy.value);
- }
- },
- {
- immediate: true,
- deep: true,
- }
-);
-
-const onRemove = async (index: number) => {
- accessUserList.value.splice(index, 1);
- state.dirty = true;
- await onSubmit();
-};
-
-const onAccessControlUpdate = async (index: number, access: AccessUser) => {
- accessUserList.value[index] = access;
- state.dirty = true;
- await onSubmit();
-};
+onMounted(() => {
+ state.maskingLevel = props.column.maskData.maskingLevel;
+ state.fullMaskingAlgorithmId = props.column.maskData.fullMaskingAlgorithmId;
+ state.partialMaskingAlgorithmId =
+ props.column.maskData.partialMaskingAlgorithmId;
+});
const onMaskingLevelUpdate = async (level: MaskingLevel) => {
state.maskingLevel = level;
@@ -434,24 +273,6 @@ const onColumnMaskingUpdate = async () => {
}
};
-const onSubmit = async () => {
- state.processing = true;
-
- try {
- if (state.dirty) {
- await updateExceptionPolicy();
- state.dirty = false;
- }
- pushNotification({
- module: "bytebase",
- style: "SUCCESS",
- title: t("common.updated"),
- });
- } finally {
- state.processing = false;
- }
-};
-
const upsertMaskingPolicy = async () => {
const policy = await policyStore.getOrFetchPolicyByParentAndType({
parentPath: props.column.database.name,
@@ -491,58 +312,6 @@ const upsertMaskingPolicy = async () => {
});
};
-const updateExceptionPolicy = async () => {
- const policy = await policyStore.getOrFetchPolicyByParentAndType({
- parentPath: props.column.database.project,
- policyType: PolicyType.MASKING_EXCEPTION,
- });
- if (!policy) {
- return;
- }
-
- const exceptions = (
- policy.maskingExceptionPolicy?.maskingExceptions ?? []
- ).filter((exception) => !isCurrentColumnException(exception, props.column));
-
- for (const accessUser of accessUserList.value) {
- const expressions = accessUser.rawExpression.split(" && ");
- 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()}")`
- );
- }
- for (const action of accessUser.supportActions) {
- exceptions.push({
- maskingLevel: accessUser.maskingLevel,
- action,
- member: getMemberBinding(accessUser),
- condition: Expr.fromPartial({
- expression: expressions.join(" && "),
- }),
- });
- }
- }
-
- policy.maskingExceptionPolicy = {
- ...(policy.maskingExceptionPolicy ?? {}),
- maskingExceptions: exceptions,
- };
- await policyStore.updatePolicy(["payload"], policy);
-};
-
const columnMetadata = computedAsync(async () => {
const { column } = props;
if (column.maskData.maskingLevel !== MaskingLevel.MASKING_LEVEL_UNSPECIFIED) {
diff --git a/frontend/src/components/SensitiveData/SensitiveColumnView.vue b/frontend/src/components/SensitiveData/SensitiveColumnView.vue
index f39b020f59..7c49ec210d 100644
--- a/frontend/src/components/SensitiveData/SensitiveColumnView.vue
+++ b/frontend/src/components/SensitiveData/SensitiveColumnView.vue
@@ -109,8 +109,8 @@
/>
<SensitiveColumnDrawer
- v-if="filteredColumnList.length > 0"
- :show="
+ v-if="
+ filteredColumnList.length > 0 &&
state.showSensitiveColumnDrawer &&
state.pendingGrantAccessColumn.length === 1
"
diff --git a/frontend/src/components/SensitiveData/types.ts b/frontend/src/components/SensitiveData/types.ts
index ebeb70da1e..80238c84cf 100644
--- a/frontend/src/components/SensitiveData/types.ts
+++ b/frontend/src/components/SensitiveData/types.ts
@@ -1,4 +1,4 @@
-import type { ComposedDatabase } from "@/types";
+import type { ComposedDatabase, DatabaseResource } from "@/types";
import { type User } from "@/types/proto/v1/auth_service";
import { MaskingLevel } from "@/types/proto/v1/common";
import type { Group } from "@/types/proto/v1/group";
@@ -21,4 +21,5 @@ export interface AccessUser {
maskingLevel: MaskingLevel;
expirationTimestamp?: number;
rawExpression: string;
+ databaseResource?: DatabaseResource;
}
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index f6efb14148..089d85d951 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -2212,7 +2212,8 @@
},
"masking-access": {
"self": "Access Masking",
- "grant-access": "Grant Access"
+ "grant-access": "Grant Access",
+ "revoke-access-title": "Remove both export and query access for {member}?"
}
},
"gitops": {
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index 9b330bf648..7d8d20e497 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -2159,8 +2159,8 @@
"description": "Se omitirán los errores de copia de seguridad y las tareas de cambio de datos continuarán ejecutándose."
},
"postgres-database-tenant-mode": {
- "description": "El modo de inquilino para la base de datos Postgres. Si está habilitado, el usuario de la base de datos ejecutará el problema.",
- "self": "Modo inquilino de base de datos Postgres"
+ "self": "Modo inquilino de base de datos Postgres",
+ "description": "El modo de inquilino para la base de datos Postgres. Si está habilitado, el usuario de la base de datos ejecutará el problema."
}
}
},
@@ -2212,7 +2212,8 @@
},
"masking-access": {
"self": "Enmascaramiento de acceso",
- "grant-access": "Conceder acceso"
+ "grant-access": "Conceder acceso",
+ "revoke-access-title": "¿Eliminar el acceso de exportación y consulta para {member}?"
}
},
"gitops": {
@@ -3823,4 +3824,4 @@
"setup": {
"self": "Configuración"
}
-}
+}
\ No newline at end of file
diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.json
index 77f3001181..f677898f0b 100644
--- a/frontend/src/locales/ja-JP.json
+++ b/frontend/src/locales/ja-JP.json
@@ -2159,8 +2159,8 @@
"description": "バックアップ エラーをスキップすると、データの変更タスクは引き続き実行されます。"
},
"postgres-database-tenant-mode": {
- "description": "Postgres データベースのテナント モード。有効にすると、問題はデータベース ユーザーによって実行されます。",
- "self": "Postgres データベーステナントモード"
+ "self": "Postgres データベーステナントモード",
+ "description": "Postgres データベースのテナント モード。有効にすると、問題はデータベース ユーザーによって実行されます。"
}
}
},
@@ -2212,7 +2212,8 @@
},
"masking-access": {
"self": "アクセスマスキング",
- "grant-access": "アクセスを許可する"
+ "grant-access": "アクセスを許可する",
+ "revoke-access-title": "{member} のエクスポート アクセスとクエリ アクセスの両方を削除しますか?"
}
},
"gitops": {
@@ -3823,4 +3824,4 @@
"setup": {
"self": "設定"
}
-}
+}
\ No newline at end of file
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index d2f2fd99b1..f8cc37e615 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -2159,8 +2159,8 @@
"description": "当备份失败时,跳过错误并且变更数据任务将继续执行。"
},
"postgres-database-tenant-mode": {
- "description": "Postgres 数据库租户模式。如果启用,工单将以数据库所有者角色执行。",
- "self": "Postgres 数据库租户模式"
+ "self": "Postgres 数据库租户模式",
+ "description": "Postgres 数据库租户模式。如果启用,工单将以数据库所有者角色执行。"
}
}
},
@@ -2212,7 +2212,8 @@
},
"masking-access": {
"self": "数据访问",
- "grant-access": "授予访问权限"
+ "grant-access": "授予访问权限",
+ "revoke-access-title": "是否删除 {member} 的导出和查询访问权限?"
}
},
"gitops": {
@@ -3823,4 +3824,4 @@
"setup": {
"self": "设置"
}
-}
+}
\ No newline at end of file
diff --git a/frontend/src/views/project/ProjectDatabaseMaskingAccess.vue b/frontend/src/views/project/ProjectDatabaseMaskingAccess.vue
index af79d6184f..a4712fbd4f 100644
--- a/frontend/src/views/project/ProjectDatabaseMaskingAccess.vue
+++ b/frontend/src/views/project/ProjectDatabaseMaskingAccess.vue
@@ -1,145 +1,25 @@
<template>
+ <!-- TODO(ed): support filter -->
<MaskingExceptionUserTable
size="medium"
- :access-list="accessList"
:disabled="false"
+ :project="project.name"
:show-database-column="true"
+ :filter-exception="(_) => true"
/>
</template>
<script lang="tsx" setup>
-import { orderBy } from "lodash-es";
import { computed } from "vue";
import MaskingExceptionUserTable from "@/components/SensitiveData/MaskingExceptionUserTable.vue";
-import type { AccessUser } from "@/components/SensitiveData/types";
import { useProjectByName } from "@/store";
-import {
- usePolicyByParentAndType,
- useUserStore,
- useGroupStore,
- extractGroupEmail,
-} from "@/store";
import { projectNamePrefix } from "@/store/modules/v1/common";
-import {
- getUserEmailInBinding,
- getGroupEmailInBinding,
- groupBindingPrefix,
-} from "@/types";
-import { maskingLevelToJSON } from "@/types/proto/v1/common";
-import { PolicyType } from "@/types/proto/v1/org_policy_service";
-import type { MaskingExceptionPolicy_MaskingException } from "@/types/proto/v1/org_policy_service";
const props = defineProps<{
projectId: string;
}>();
-const userStore = useUserStore();
-const groupStore = useGroupStore();
-
const { project } = useProjectByName(
computed(() => `${projectNamePrefix}${props.projectId}`)
);
-
-const policy = usePolicyByParentAndType(
- computed(() => ({
- parentPath: project.value.name,
- policyType: PolicyType.MASKING_EXCEPTION,
- }))
-);
-
-const expirationTimeRegex = /request.time < timestamp\("(.+)?"\)/;
-
-const getAccessUsers = (
- exception: MaskingExceptionPolicy_MaskingException
-): AccessUser | undefined => {
- let expirationTimestamp: number | undefined;
- const expression = exception.condition?.expression ?? "";
- const matches = expirationTimeRegex.exec(expression);
- if (matches) {
- expirationTimestamp = new Date(matches[1]).getTime();
- }
-
- const access: AccessUser = {
- type: "user",
- key: exception.member,
- maskingLevel: exception.maskingLevel,
- expirationTimestamp,
- supportActions: new Set([exception.action]),
- rawExpression: expression,
- };
-
- if (exception.member.startsWith(groupBindingPrefix)) {
- access.type = "group";
- access.group = groupStore.getGroupByIdentifier(exception.member);
- } else {
- access.type = "user";
- access.user = userStore.getUserByIdentifier(exception.member);
- }
-
- if (!access.group && !access.user) {
- return;
- }
-
- return access;
-};
-
-const getExceptionIdentifier = (
- exception: MaskingExceptionPolicy_MaskingException
-): string => {
- const expression = exception.condition?.expression ?? "";
- const res: string[] = [
- `level:"${maskingLevelToJSON(exception.maskingLevel)}"`,
- expression,
- ];
- return res.join(" && ");
-};
-
-const getMemberBinding = (access: AccessUser): string => {
- if (access.type === "user") {
- return getUserEmailInBinding(access.user!.email);
- }
- const email = extractGroupEmail(access.group!.name);
- return getGroupEmailInBinding(email);
-};
-
-const accessList = computed(() => {
- if (!policy.value || !policy.value.maskingExceptionPolicy) {
- return [];
- }
-
- const memberMap = new Map<string, AccessUser>();
- for (const exception of policy.value.maskingExceptionPolicy
- .maskingExceptions) {
- const identifier = getExceptionIdentifier(exception);
- const item = getAccessUsers(exception);
- if (!item) {
- continue;
- }
- const id = `${getMemberBinding(item)}:${identifier}`;
- item.key = id;
- const target = memberMap.get(id) ?? item;
- if (memberMap.has(id)) {
- for (const action of item.supportActions) {
- target.supportActions.add(action);
- }
- }
- memberMap.set(id, target);
- }
-
- return orderBy(
- [...memberMap.values()],
- [
- (access) => (access.type === "user" ? 1 : 0),
- (access) => {
- if (access.group) {
- return access.group.name;
- } else if (access.user) {
- return access.user.name;
- }
- return "";
- },
- ],
- ["desc", "desc"]
- );
-});
</script>