Skip to content

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

feat: update data access control setting page (#6860)

boojack5bdc50d8a220
diff --git a/backend/api/v1/org_policy_service.go b/backend/api/v1/org_policy_service.go
index dcf3bc1c0a..4c7fda99eb 100644
--- a/backend/api/v1/org_policy_service.go
+++ b/backend/api/v1/org_policy_service.go
@@ -8,7 +8,7 @@ import (
"go.uber.org/zap"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
- "google.golang.org/protobuf/proto"
+ "google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/types/known/durationpb"
"google.golang.org/protobuf/types/known/emptypb"
@@ -458,8 +458,12 @@ func validatePolicyType(policyType api.PolicyType, policyResourceType api.Policy
func convertPolicyPayloadToString(policy *v1pb.Policy) (string, error) {
switch policy.Type {
case v1pb.PolicyType_WORKSPACE_IAM:
- payload := convertToStorePBWorkspaceIAMPolicy(policy.GetWorkspaceIamPolicy())
- return payload.String(), nil
+ iamPolicy := convertToStorePBWorkspaceIAMPolicy(policy.GetWorkspaceIamPolicy())
+ payloadBytes, err := protojson.Marshal(iamPolicy)
+ if err != nil {
+ return "", errors.Wrap(err, "failed to marshal workspace iam policy")
+ }
+ return string(payloadBytes), nil
case v1pb.PolicyType_DEPLOYMENT_APPROVAL:
payload, err := convertToPipelineApprovalPolicyPayload(policy.GetDeploymentApprovalPolicy())
if err != nil {
@@ -557,7 +561,7 @@ func convertToPolicy(parentPath string, policyMessage *store.PolicyMessage) (*v1
case api.PolicyTypeWorkspaceIAM:
pType = v1pb.PolicyType_WORKSPACE_IAM
storepbIAMPolicy := &storepb.IamPolicy{}
- err := proto.Unmarshal([]byte(policyMessage.Payload), storepbIAMPolicy)
+ err := protojson.Unmarshal([]byte(policyMessage.Payload), storepbIAMPolicy)
if err != nil {
return nil, errors.Wrap(err, "failed to unmarshal workspace IAM policy")
}
@@ -624,23 +628,26 @@ func convertToV1PBWorkspaceIAMPolicy(policy *storepb.IamPolicy) (*v1pb.Policy_Wo
Bindings: []*v1pb.Binding{},
}
for _, binding := range policy.Bindings {
+ v1pbBinding := v1pb.Binding{
+ Role: binding.Role,
+ Members: binding.Members,
+ Condition: binding.Condition,
+ }
+
env, err := cel.NewEnv(iamPolicyCELAttributes...)
if err != nil {
return nil, errors.Wrap(err, "failed to create cel environment")
}
- ast, issues := env.Parse(binding.Condition.Expression)
- if issues != nil && issues.Err() != nil {
- return nil, errors.Wrap(issues.Err(), "failed to parse expression")
- }
- parsedExpr, err := cel.AstToParsedExpr(ast)
- if err != nil {
- return nil, errors.Wrap(err, "failed to convert ast to parsed expression")
- }
- v1pbBinding := v1pb.Binding{
- Role: binding.Role,
- Members: binding.Members,
- Condition: binding.Condition,
- ParsedExpr: parsedExpr,
+ if binding.Condition.Expression != "" {
+ ast, issues := env.Parse(binding.Condition.Expression)
+ if issues != nil && issues.Err() != nil {
+ return nil, errors.Wrap(issues.Err(), "failed to parse expression")
+ }
+ parsedExpr, err := cel.AstToParsedExpr(ast)
+ if err != nil {
+ return nil, errors.Wrap(err, "failed to convert ast to parsed expression")
+ }
+ v1pbBinding.ParsedExpr = parsedExpr
}
iamPolicy.Bindings = append(iamPolicy.Bindings, &v1pbBinding)
}
diff --git a/frontend/src/components/AccessControl/AddRuleForm.vue b/frontend/src/components/AccessControl/AddRuleForm.vue
deleted file mode 100644
index 3f1864d064..0000000000
--- a/frontend/src/components/AccessControl/AddRuleForm.vue
+++ /dev/null
@@ -1,214 +0,0 @@
-<template>
- <DrawerContent :title="$t('settings.access-control.add-rule')">
- <div class="w-[calc(100vw-8rem)] max-w-[60rem] space-y-2 relative">
- <div>
- <SearchBox
- v-model:value="state.searchText"
- style="width: 15rem"
- :placeholder="$t('database.search-database')"
- />
- </div>
-
- <DatabaseV1Table
- mode="ALL_TINY"
- table-class="border"
- :custom-click="true"
- :database-list="databaseList"
- :show-selection-column="true"
- @select-database="
- (db: ComposedDatabase) => toggleDatabaseSelection(db, !isDatabaseSelected(db))
- "
- >
- <template #selection-all="{ databaseList: renderedDatabaseList }">
- <input
- v-if="renderedDatabaseList.length > 0"
- type="checkbox"
- class="h-4 w-4 text-accent rounded disabled:cursor-not-allowed border-control-border focus:ring-accent"
- v-bind="getAllSelectionState(renderedDatabaseList)"
- @input="
- toggleAllDatabasesSelection(
- renderedDatabaseList,
- ($event.target as HTMLInputElement).checked
- )
- "
- />
- </template>
- <template #selection="{ database }">
- <input
- type="checkbox"
- class="h-4 w-4 text-accent rounded disabled:cursor-not-allowed border-control-border focus:ring-accent"
- :checked="isDatabaseSelected(database)"
- @input="(e: any) => toggleDatabaseSelection(database, e.target.checked)"
- />
- </template>
- </DatabaseV1Table>
-
- <div
- v-if="!state.isLoading && databaseList.length === 0"
- class="w-full flex flex-col py-6 justify-start items-center"
- >
- <i18n-t
- keypath="settings.access-control.no-database-in-production-environment"
- tag="div"
- class="text-sm leading-6 text-gray-500 max-w-[15rem] whitespace-pre-wrap text-center"
- >
- <template #production_environment>
- <a
- href="https://www.bytebase.com/docs/security/data-access-control"
- class="normal-link lowercase"
- target="_BLANK"
- >
- {{ $t("environment.production-environment") }}
- <heroicons-outline:external-link
- class="inline-block w-4 h-4 -mt-0.5 mr-0.5"
- />
- </a>
- </template>
- </i18n-t>
- </div>
-
- <div
- v-if="state.isLoading"
- class="absolute w-full h-full inset-0 bg-white/50 flex flex-col items-center justify-center"
- >
- <BBSpin />
- </div>
- </div>
-
- <template #footer>
- <div class="flex items-center justify-between">
- <div class="textinfolabel">
- <template v-if="state.selectedDatabaseIdList.size > 0">
- {{
- $t("database.selected-n-databases", {
- n: state.selectedDatabaseIdList.size,
- })
- }}
- </template>
- </div>
- <div class="flex items-center gap-x-2">
- <button class="btn-normal" @click="$emit('cancel')">
- {{ $t("common.cancel") }}
- </button>
- <button class="btn-primary" :disabled="!allowAdd" @click="tryAdd">
- {{ $t("common.add") }}
- </button>
- </div>
- </div>
- </template>
- </DrawerContent>
-</template>
-
-<script lang="ts" setup>
-import { computed, PropType, reactive } from "vue";
-
-import type { ComposedDatabase } from "@/types";
-import { filterDatabaseV1ByKeyword } from "@/utils";
-import { Policy } from "@/types/proto/v1/org_policy_service";
-import { SearchBox, DrawerContent } from "@/components/v2";
-
-type LocalState = {
- isLoading: boolean;
- searchText: string;
- selectedDatabaseIdList: Set<string>;
-};
-
-const props = defineProps({
- policyList: {
- type: Array as PropType<Policy[]>,
- default: () => [],
- },
- databaseList: {
- type: Array as PropType<ComposedDatabase[]>,
- default: () => [],
- },
-});
-
-const emit = defineEmits<{
- (e: "cancel"): void;
- (e: "add", databaseList: ComposedDatabase[]): void;
-}>();
-
-const state = reactive<LocalState>({
- isLoading: false,
- searchText: "",
- selectedDatabaseIdList: new Set(),
-});
-
-const presetDatabaseIdList = computed(() => {
- const databaseIdList = props.policyList.map(
- (policy) => policy.resourceUid as string
- );
- return new Set(databaseIdList);
-});
-
-const databaseList = computed(() => {
- // Don't show the databases already have access control policy.
- let list = props.databaseList.filter(
- (db) => !presetDatabaseIdList.value.has(db.uid)
- );
-
- const keyword = state.searchText.trim();
- list = list.filter((db) =>
- filterDatabaseV1ByKeyword(db, keyword, [
- "name",
- "project",
- "instance",
- "environment",
- ])
- );
- return list;
-});
-
-const allowAdd = computed(() => {
- return state.selectedDatabaseIdList.size > 0;
-});
-
-const tryAdd = () => {
- const selectedDatabaseList = databaseList.value.filter((db) =>
- isDatabaseSelected(db)
- );
- emit("add", selectedDatabaseList);
-};
-
-const toggleDatabaseSelection = (database: ComposedDatabase, on: boolean) => {
- if (on) {
- state.selectedDatabaseIdList.add(database.uid);
- } else {
- state.selectedDatabaseIdList.delete(database.uid);
- }
-};
-
-const isDatabaseSelected = (database: ComposedDatabase) => {
- return state.selectedDatabaseIdList.has(database.uid);
-};
-
-const getAllSelectionState = (
- databaseList: ComposedDatabase[]
-): { checked: boolean; indeterminate: boolean } => {
- const checked = databaseList.every((db) => isDatabaseSelected(db));
- const indeterminate =
- !checked && databaseList.some((db) => isDatabaseSelected(db));
-
- return {
- checked,
- indeterminate,
- };
-};
-
-const toggleAllDatabasesSelection = (
- databaseList: ComposedDatabase[],
- on: boolean
-): void => {
- const set = state.selectedDatabaseIdList;
- if (on) {
- databaseList.forEach((db) => {
- set.add(db.uid);
- });
- } else {
- databaseList.forEach((db) => {
- set.delete(db.uid);
- });
- }
-};
-</script>
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index a40c629d0b..a9bc5318dc 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -561,12 +561,10 @@
"remove-sensitive-column-tips": "Expose this column?"
},
"access-control": {
- "description": "Allow developers to execute queries for the following databases in the production environments from SQL Editor. {link}",
- "add-rule": "Add rule",
- "remove-policy-tips": "Remove this rule?",
- "inactive-rules": "Inactive rules",
- "inactive-rules-description": "These rules are inactive because environment is not production.",
- "no-database-in-production-environment": "Make sure there are databases in the {production_environment}."
+ "description": "Configure approval flow to control data query and export. {link}",
+ "skip-approval": "Skip approval",
+ "query-data": "Query Data",
+ "export-data": "Export Data"
},
"release": {
"new-version-available": "New version is available",
@@ -1952,8 +1950,8 @@
"desc": "Mark table columns as sensitive data and the query result of them will be displayed as \"******\"."
},
"bb-feature-access-control": {
- "title": "Access control",
- "desc": "Change query permission for databases in the production environments."
+ "title": "Data Access control",
+ "desc": "Configure approval flow to control data query and export."
},
"bb-feature-lgtm": {
"title": "LGTM check",
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index 8c2d44a843..dd8c7574ab 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -554,12 +554,10 @@
"remove-sensitive-column-tips": "¿Exponer esta columna?"
},
"access-control": {
- "description": "Permitir a los desarrolladores ejecutar consultas para las siguientes bases de datos en ambientes de producción desde el Editor de SQL. {link}",
- "add-rule": "Añadir regla",
- "remove-policy-tips": "¿Eliminar esta regla?",
- "inactive-rules": "Reglas inactivas",
- "inactive-rules-description": "Estas reglas están inactivas porque el ambiente no es de producción.",
- "no-database-in-production-environment": "Asegúrese de que hay bases de datos en el {production_environment}."
+ "description": "Configura un flujo de aprobación para controlar la consulta y exportación de datos. {link}",
+ "skip-approval": "Saltar aprobación manual",
+ "query-data": "Consulta de datos",
+ "export-data": "Exportación de datos"
},
"release": {
"new-version-available": "Nueva versión disponible",
@@ -1938,8 +1936,8 @@
"desc": "Marque las columnas de la tabla como datos sensibles y el resultado de la consulta de ellos se mostrará como \"******\"."
},
"bb-feature-access-control": {
- "title": "Control de acceso",
- "desc": "Cambie el permiso de consulta para bases de datos en entornos de producción."
+ "title": "Control de acceso a datos",
+ "desc": "Configura un flujo de aprobación para controlar la consulta y exportación de datos."
},
"bb-feature-lgtm": {
"title": "Verificación LGTM",
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index 21f3b3d858..75cd6a9850 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -558,12 +558,10 @@
"remove-sensitive-column-tips": "不再对此列数据脱敏?"
},
"access-control": {
- "description": "允许开发者通过 SQL 编辑器对下列生产环境中的数据库执行查询。{link}",
- "add-rule": "添加规则",
- "remove-policy-tips": "删除这条规则?",
- "inactive-rules": "无效的规则",
- "inactive-rules-description": "这些规则不再生效,因为不属于生产环境。",
- "no-database-in-production-environment": "请确保{production_environment}中有数据库。"
+ "description": "配置审批流来控制数据的查询和导出。{link}",
+ "skip-approval": "跳过人工审批",
+ "query-data": "数据查询",
+ "export-data": "数据导出"
},
"release": {
"new-version-available": "有新版本可更新",
@@ -1947,8 +1945,8 @@
"desc": "将数据表的列标记为敏感数据,它们在查询结果中将会被显示成 \"******\"。"
},
"bb-feature-access-control": {
- "title": "访问控制",
- "desc": "可以修改生产环境中的数据库的查询权限。"
+ "title": "数据访问控制",
+ "desc": "配置审批流来控制数据的查询和导出。"
},
"bb-feature-lgtm": {
"title": "LGTM 检查",
diff --git a/frontend/src/views/SettingWorkspaceAccessControl.vue b/frontend/src/views/SettingWorkspaceAccessControl.vue
index 230a835929..dd09c6e91b 100644
--- a/frontend/src/views/SettingWorkspaceAccessControl.vue
+++ b/frontend/src/views/SettingWorkspaceAccessControl.vue
@@ -1,7 +1,7 @@
<template>
<div class="w-full mt-4 space-y-4">
<FeatureAttention
- v-if="!hasAccessControlFeature"
+ v-if="!hasDataAccessControlFeature"
feature="bb.feature.access-control"
/>
<div class="flex justify-between">
@@ -16,169 +16,65 @@
/>
</template>
</i18n-t>
-
- <div>
- <button
- class="btn-primary whitespace-nowrap"
- :disabled="!allowAdmin || !hasAccessControlFeature"
- @click="state.showAddRuleModal = true"
- >
- {{ $t("settings.access-control.add-rule") }}
- </button>
- </div>
</div>
- <div v-if="hasAccessControlFeature" class="relative min-h-[12rem]">
+ <div class="relative">
<BBTable
:column-list="COLUMN_LIST"
- :data-source="activePolicyList"
+ :data-source="state.environmentPolicyList"
:show-header="true"
:left-bordered="true"
:right-bordered="true"
:row-clickable="false"
>
- <template #body="{ rowData: policy }: { rowData: Policy }">
- <BBTableCell class="w-[25%]" :left-padding="4">
- <DatabaseV1Name
- :database="databaseOfPolicy(policy)"
- :link="false"
- />
- </BBTableCell>
- <BBTableCell class="w-[15%]">
- <ProjectV1Name
- :project="databaseOfPolicy(policy).projectEntity"
- :link="false"
- />
- </BBTableCell>
- <BBTableCell class="w-[15%]">
+ <template #body="{ rowData: policy }: { rowData: EnvironmentPolicy }">
+ <BBTableCell>
<EnvironmentV1Name
- :environment="
- databaseOfPolicy(policy).instanceEntity.environmentEntity
- "
+ class="pl-2"
+ :environment="policy.environment"
:link="false"
/>
</BBTableCell>
- <BBTableCell class="w-[15%]">
- <InstanceV1Name
- :instance="databaseOfPolicy(policy).instanceEntity"
- :link="false"
- />
+ <BBTableCell>
+ <NCheckbox
+ v-model:checked="policy.allowQueryData"
+ :disabled="!allowAdmin"
+ >
+ {{ $t("settings.access-control.skip-approval") }}
+ </NCheckbox>
</BBTableCell>
<BBTableCell>
- <div class="flex items-center justify-center">
- <NPopconfirm @positive-click="handleRemove(policy)">
- <template #trigger>
- <button
- :disabled="!allowAdmin"
- class="w-5 h-5 p-0.5 bg-white hover:bg-control-bg-hover rounded cursor-pointer disabled:cursor-not-allowed disabled:hover:bg-white disabled:text-gray-400"
- >
- <heroicons-outline:trash />
- </button>
- </template>
-
- <div class="whitespace-nowrap">
- {{ $t("settings.access-control.remove-policy-tips") }}
- </div>
- </NPopconfirm>
- </div>
+ <NCheckbox
+ v-model:checked="policy.allowExportData"
+ :disabled="!allowAdmin"
+ >
+ {{ $t("settings.access-control.skip-approval") }}
+ </NCheckbox>
</BBTableCell>
</template>
</BBTable>
<div
- v-if="!state.isLoading && activePolicyList.length === 0"
- class="w-full flex flex-col py-6 justify-start items-center"
+ v-if="state.isLoading"
+ class="absolute w-full h-full inset-0 z-1 bg-white/50 flex flex-col items-center justify-center"
>
- <heroicons-outline:inbox class="w-12 h-auto text-gray-500" />
- <span class="text-sm leading-6 text-gray-500">{{
- $t("common.no-data")
- }}</span>
+ <BBSpin />
</div>
- <template v-if="inactivePolicyList.length > 0">
- <div class="text-lg mt-6 mb-1">
- {{ $t("settings.access-control.inactive-rules") }}
- </div>
- <div class="textinfolabel max-w-xl mb-4">
- {{ $t("settings.access-control.inactive-rules-description") }}
- </div>
- <BBTable
- :column-list="COLUMN_LIST"
- :data-source="inactivePolicyList"
- :show-header="true"
- :left-bordered="true"
- :right-bordered="true"
- :row-clickable="false"
- >
- <template #body="{ rowData: policy }: { rowData: Policy }">
- <BBTableCell class="w-[25%]" :left-padding="4">
- <div class="flex items-center space-x-2">
- <span>{{ databaseOfPolicy(policy).name }}</span>
- </div>
- </BBTableCell>
- <BBTableCell class="w-[15%]">
- <ProjectV1Name
- :project="databaseOfPolicy(policy).projectEntity"
- :link="false"
- />
- </BBTableCell>
- <BBTableCell class="w-[15%]">
- <EnvironmentV1Name
- :environment="
- databaseOfPolicy(policy).instanceEntity.environmentEntity
- "
- :link="false"
- />
- </BBTableCell>
- <BBTableCell class="w-[15%]">
- <InstanceV1Name
- :instance="databaseOfPolicy(policy).instanceEntity"
- :link="false"
- />
- </BBTableCell>
- <BBTableCell>
- <div class="flex items-center justify-center">
- <NPopconfirm @positive-click="handleRemove(policy)">
- <template #trigger>
- <button
- :disabled="!allowAdmin"
- class="w-5 h-5 p-0.5 bg-white hover:bg-control-bg-hover rounded cursor-pointer disabled:cursor-not-allowed disabled:hover:bg-white disabled:text-gray-400"
- >
- <heroicons-outline:trash />
- </button>
- </template>
-
- <div class="whitespace-nowrap">
- {{ $t("settings.access-control.remove-policy-tips") }}
- </div>
- </NPopconfirm>
- </div>
- </BBTableCell>
- </template>
- </BBTable>
- </template>
-
<div
- v-if="state.isLoading || state.isUpdating"
- class="absolute w-full h-full inset-0 bg-white/50 flex flex-col items-center justify-center"
+ v-if="!hasDataAccessControlFeature"
+ class="absolute w-full h-full inset-0 z-10 bg-gray-300/80 flex flex-col items-center justify-center"
>
- <BBSpin />
+ <button
+ type="button"
+ class="btn-primary whitespace-nowrap shadow"
+ @click.prevent="handleUpgradeSubscription"
+ >
+ <heroicons-solid:sparkles class="text-white w-5 h-auto mr-1" />
+ {{ $t("subscription.upgrade") }}
+ </button>
</div>
</div>
-
- <template v-else>
- <BBTable
- :column-list="COLUMN_LIST"
- :data-source="[]"
- :show-header="true"
- :left-bordered="true"
- :right-bordered="true"
- :row-clickable="false"
- />
- <div class="w-full h-full flex flex-col items-center justify-center">
- <img src="../assets/illustration/no-data.webp" class="max-h-[30vh]" />
- </div>
- </template>
</div>
<FeatureModal
@@ -186,68 +82,60 @@
feature="bb.feature.access-control"
@cancel="state.showFeatureModal = false"
/>
-
- <Drawer
- :show="state.showAddRuleModal"
- @close="state.showAddRuleModal = false"
- >
- <AddRuleForm
- :policy-list="state.policyList"
- :database-list="state.databaseList"
- @cancel="state.showAddRuleModal = false"
- @add="handleAddRule"
- />
- </Drawer>
</template>
<script lang="ts" setup>
-import { computed, reactive, watchEffect } from "vue";
+import { NCheckbox } from "naive-ui";
+import { computed, reactive, watch, onMounted } from "vue";
import { useI18n } from "vue-i18n";
-import { NPopconfirm } from "naive-ui";
-import { uniq } from "lodash-es";
-import { featureToRef, useCurrentUserV1, useDatabaseV1Store } from "@/store";
-import { ComposedDatabase, DEFAULT_PROJECT_V1_NAME } from "@/types";
+import { featureToRef, useCurrentUserV1, useEnvironmentV1List } from "@/store";
import { BBTableColumn } from "@/bbkit/types";
import { hasWorkspacePermissionV1 } from "@/utils";
-import { Drawer } from "@/components/v2";
-import AddRuleForm from "@/components/AccessControl/AddRuleForm.vue";
import { usePolicyV1Store } from "@/store/modules/v1/policy";
+import { Environment } from "@/types/proto/v1/environment_service";
+import { EnvironmentV1Name } from "@/components/v2";
+import { resolveCELExpr } from "@/plugins/cel";
import {
- Policy,
- PolicyType,
PolicyResourceType,
+ PolicyType,
} from "@/types/proto/v1/org_policy_service";
-import { EnvironmentTier } from "@/types/proto/v1/environment_service";
-import {
- InstanceV1Name,
- ProjectV1Name,
- EnvironmentV1Name,
-} from "@/components/v2";
+import { IamPolicy } from "@/types/proto/v1/iam_policy";
+import { Expr } from "@/types/proto/google/type/expr";
+import { useDebounceFn } from "@vueuse/core";
+import { useRouter } from "vue-router";
+
+interface EnvironmentPolicy {
+ environment: Environment;
+ allowQueryData: boolean;
+ allowExportData: boolean;
+}
interface LocalState {
showFeatureModal: boolean;
- showAddRuleModal: boolean;
isLoading: boolean;
- isUpdating: boolean;
- policyList: Policy[];
- databaseList: ComposedDatabase[];
+ environmentPolicyList: EnvironmentPolicy[];
}
const { t } = useI18n();
+const router = useRouter();
+const environmentList = useEnvironmentV1List();
+const policyStore = usePolicyV1Store();
+const currentUserV1 = useCurrentUserV1();
+const hasDataAccessControlFeature = featureToRef("bb.feature.access-control");
const state = reactive<LocalState>({
showFeatureModal: false,
- showAddRuleModal: false,
- isLoading: false,
- isUpdating: false,
- policyList: [],
- databaseList: [],
+ isLoading: true,
+ environmentPolicyList: environmentList.value.map((environment) => {
+ const defaultValue = hasDataAccessControlFeature.value ? false : true;
+ return {
+ environment,
+ allowQueryData: defaultValue,
+ allowExportData: defaultValue,
+ };
+ }),
});
-const databaseStore = useDatabaseV1Store();
-const policyStore = usePolicyV1Store();
-const hasAccessControlFeature = featureToRef("bb.feature.access-control");
-const currentUserV1 = useCurrentUserV1();
const allowAdmin = computed(() => {
return hasWorkspacePermissionV1(
"bb.permission.workspace.manage-access-control",
@@ -255,129 +143,120 @@ const allowAdmin = computed(() => {
);
});
-const databaseOfPolicy = (policy: Policy) => {
- return databaseStore.getDatabaseByUID(policy.resourceUid);
-};
-
-const activePolicyList = computed(() => {
- return state.policyList.filter(
- (policy) =>
- databaseOfPolicy(policy).instanceEntity.environmentEntity.tier ===
- EnvironmentTier.PROTECTED
- );
-});
-
-const inactivePolicyList = computed(() => {
- return state.policyList.filter(
- (policy) =>
- databaseOfPolicy(policy).instanceEntity.environmentEntity.tier ===
- EnvironmentTier.UNPROTECTED
- );
-});
-
-const prepareList = async () => {
- state.isLoading = true;
-
- const policyList = await policyStore.fetchPolicies({
- policyType: PolicyType.ACCESS_CONTROL,
- resourceType: PolicyResourceType.DATABASE,
- });
-
- const allDatabaseList = await databaseStore.fetchDatabaseList({
- parent: "instances/-",
- });
- state.databaseList = allDatabaseList
- .filter(
- (db) =>
- db.instanceEntity.environmentEntity.tier === EnvironmentTier.PROTECTED
- )
- .filter((db) => db.project !== DEFAULT_PROJECT_V1_NAME);
-
- // For some policy related databases that are not in the state.databaseList,
- // fetch them.
- const databaseIdList = uniq(
- policyList
- .map((policy) => policy.resourceUid)
- .filter((databaseId) =>
- state.databaseList.findIndex((db) => db.uid == databaseId)
- )
- );
+const COLUMN_LIST = computed((): BBTableColumn[] => [
+ {
+ title: t("common.environment"),
+ },
+ {
+ title: t("settings.access-control.query-data"),
+ },
+ {
+ title: t("settings.access-control.export-data"),
+ },
+]);
- Promise.all(
- databaseIdList.map((databaseId) =>
- databaseStore.getOrFetchDatabaseByUID(databaseId)
- )
+onMounted(async () => {
+ const policy = await policyStore.getOrFetchPolicyByName(
+ "policies/WORKSPACE_IAM"
);
+ if (!policy || !policy.workspaceIamPolicy) {
+ state.isLoading = false;
+ return;
+ }
- state.policyList = policyList;
+ for (const binding of policy.workspaceIamPolicy.bindings) {
+ if (!binding.members.includes("allUsers")) {
+ continue;
+ }
+ if (binding.parsedExpr?.expr) {
+ const simpleExpr = resolveCELExpr(binding.parsedExpr.expr);
+ const args = simpleExpr.args;
+ if (
+ simpleExpr.operator !== "@in" ||
+ args[0] !== "resource.environment_name"
+ ) {
+ continue;
+ }
+
+ const environmentNameList = args[1] as string[];
+ for (const environmentPolicy of state.environmentPolicyList) {
+ if (environmentNameList.includes(environmentPolicy.environment.name)) {
+ if (binding.role === "roles/QUERIER") {
+ environmentPolicy.allowQueryData = true;
+ } else if (binding.role === "roles/EXPORTER") {
+ environmentPolicy.allowExportData = true;
+ }
+ }
+ }
+ }
+ }
state.isLoading = false;
-};
+});
-watchEffect(prepareList);
+const handleUpgradeSubscription = () => {
+ router.push({ name: "setting.workspace.subscription" });
+};
-const handleAddRule = async (databaseList: ComposedDatabase[]) => {
- if (!hasAccessControlFeature.value) {
- state.showFeatureModal = true;
- return;
+const buildWorkspaceIAMPolicy = (envPolicyList: EnvironmentPolicy[]) => {
+ const workspaceIamPolicy: IamPolicy = IamPolicy.fromPartial({});
+
+ const allowQueryEnvNameList: string[] = envPolicyList
+ .filter((item) => item.allowQueryData)
+ .map((item) => item.environment.name);
+ const allowExportEnvNameList: string[] = envPolicyList
+ .filter((item) => item.allowExportData)
+ .map((item) => item.environment.name);
+ if (allowQueryEnvNameList.length > 0) {
+ workspaceIamPolicy.bindings.push({
+ role: "roles/QUERIER",
+ members: ["allUsers"],
+ condition: Expr.fromPartial({
+ expression: `resource.environment_name in ["${allowQueryEnvNameList.join(
+ '", "'
+ )}"]`,
+ }),
+ });
}
-
- state.showAddRuleModal = false;
- state.isUpdating = true;
- try {
- for (let i = 0; i < databaseList.length; i++) {
- const database = databaseList[i];
- await policyStore.upsertPolicy({
- parentPath: database.name,
- updateMask: ["payload", "inherit_from_parent"],
- policy: {
- type: PolicyType.ACCESS_CONTROL,
- inheritFromParent: false,
- accessControlPolicy: {
- disallowRules: [],
- },
- },
- });
- }
- } finally {
- state.isUpdating = false;
+ if (allowExportEnvNameList.length > 0) {
+ workspaceIamPolicy.bindings.push({
+ role: "roles/EXPORTER",
+ members: ["allUsers"],
+ condition: Expr.fromPartial({
+ expression: `resource.environment_name in ["${allowExportEnvNameList.join(
+ '", "'
+ )}"]`,
+ }),
+ });
}
- prepareList();
+ return workspaceIamPolicy;
};
-const handleRemove = async (policy: Policy) => {
- if (!hasAccessControlFeature.value) {
+const upsertWorkspaceIAMPolicy = useDebounceFn(async () => {
+ if (!hasDataAccessControlFeature.value) {
state.showFeatureModal = true;
return;
}
- state.isUpdating = true;
- try {
- await policyStore.deletePolicy(policy.name);
-
- prepareList();
- } finally {
- state.isUpdating = false;
+ if (!allowAdmin.value) {
+ return;
}
-};
-const COLUMN_LIST = computed((): BBTableColumn[] => [
- {
- title: t("common.database"),
- },
- {
- title: t("common.project"),
- },
- {
- title: t("common.environment"),
- },
- {
- title: t("common.instance"),
+ await policyStore.createPolicy("", {
+ type: PolicyType.WORKSPACE_IAM,
+ resourceType: PolicyResourceType.WORKSPACE,
+ resourceUid: "1",
+ workspaceIamPolicy: buildWorkspaceIAMPolicy(state.environmentPolicyList),
+ });
+}, 200);
+
+watch(
+ () => state.environmentPolicyList,
+ async () => {
+ await upsertWorkspaceIAMPolicy();
},
{
- title: t("common.operation"),
- center: true,
- nowrap: true,
- },
-]);
+ deep: true,
+ }
+);
</script>