Skip to content

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

feat(frontend): Risk center (#5175)

Liu Ji7f907ca03ba4
diff --git a/frontend/naive-ui.config.ts b/frontend/naive-ui.config.ts
index accab2a0b9..1b23b96d5b 100644
--- a/frontend/naive-ui.config.ts
+++ b/frontend/naive-ui.config.ts
@@ -29,23 +29,14 @@ export const themeOverrides = computed((): GlobalThemeOverrides => {
warningColorHover: callVar("--color-warning-hover"),
warningColorPressed: callVar("--color-warning"),
+ infoColor: callVar("--color-info"),
+ infoColorHover: callVar("--color-info-hover"),
+ infoColorPressed: callVar("--color-info"),
+
errorColor: callVar("--color-error"),
errorColorHover: callVar("--color-error-hover"),
errorColorPressed: callVar("--color-error"),
},
- Button: {
- colorInfo: callVar("--color-accent"),
- colorHoverInfo: callVar("--color-accent-hover"),
- colorPressedInfo: callVar("--color-accent-disabled"),
- colorFocusInfo: callVar("--color-accent"),
- colorDisabledInfo: callVar("--color-accent-disabled"),
- borderInfo: callVar("--color-accent"),
- borderHoverInfo: callVar("--color-accent-hover"),
- borderFocusInfo: callVar("--color-accent"),
- },
- Dialog: {
- iconColorInfo: callVar("--color-accent"),
- },
};
});
diff --git a/frontend/src/bbkit/BBGrid/BBGrid.vue b/frontend/src/bbkit/BBGrid/BBGrid.vue
index 444ce352a5..891448a422 100644
--- a/frontend/src/bbkit/BBGrid/BBGrid.vue
+++ b/frontend/src/bbkit/BBGrid/BBGrid.vue
@@ -22,7 +22,7 @@
<div
v-for="(item, row) in dataSource"
- :key="row"
+ :key="rowKey ? item[rowKey] : row"
row="table-row"
class="bb-grid-row group"
:class="{
@@ -32,6 +32,17 @@
>
<slot name="item" :item="item" :row="row" />
</div>
+ <slot name="placeholder">
+ <div
+ v-if="dataSource.length === 0 && showPlaceholder"
+ class="flex flex-col items-center justify-center py-8 text-control-placeholder border-t"
+ :style="{
+ 'grid-column': `auto / span ${columnList.length}`,
+ }"
+ >
+ <p>{{ $t("common.no-data") }}</p>
+ </div>
+ </slot>
</div>
<slot name="footer" />
@@ -59,6 +70,7 @@ const props = withDefaults(
defineProps<{
columnList?: BBGridColumn[];
dataSource?: DataType[];
+ rowKey?: string;
showHeader?: boolean;
customHeader?: boolean;
headerClass?: VueClass;
@@ -68,11 +80,12 @@ const props = withDefaults(
{
columnList: () => [],
dataSource: () => [],
+ rowKey: undefined,
showHeader: true,
customHeader: false,
headerClass: undefined,
rowClickable: true,
- showPlaceholder: true,
+ showPlaceholder: false,
}
);
diff --git a/frontend/src/bbkit/BBModal.vue b/frontend/src/bbkit/BBModal.vue
index 6456814992..9feb290b75 100644
--- a/frontend/src/bbkit/BBModal.vue
+++ b/frontend/src/bbkit/BBModal.vue
@@ -86,6 +86,10 @@ export default defineComponent({
type: Boolean,
default: true,
},
+ beforeClose: {
+ type: Function as PropType<() => Promise<boolean>>,
+ default: undefined,
+ },
},
emits: ["close"],
setup(props, { emit }) {
@@ -100,7 +104,12 @@ export default defineComponent({
subtitle: undefined,
});
- const close = () => {
+ const close = async () => {
+ const { beforeClose } = props;
+ if (beforeClose) {
+ const pass = await beforeClose();
+ if (!pass) return;
+ }
emit("close");
};
diff --git a/frontend/src/components/CustomApproval/Settings/components/RiskCenter/RiskCenter.vue b/frontend/src/components/CustomApproval/Settings/components/RiskCenter/RiskCenter.vue
new file mode 100644
index 0000000000..1f04a97ffa
--- /dev/null
+++ b/frontend/src/components/CustomApproval/Settings/components/RiskCenter/RiskCenter.vue
@@ -0,0 +1,98 @@
+<template>
+ <div class="w-full">
+ <RiskNavigation class="my-4">
+ <template #suffix>
+ <NButton type="primary" :disabled="!allowAdmin" @click="addRisk">
+ {{ $t("custom-approval.security-rule.add-rule") }}
+ </NButton>
+ </template>
+ </RiskNavigation>
+
+ <div class="space-y-4">
+ <RiskSection
+ v-for="{ source, riskList } in riskListGroupBySource"
+ :key="source"
+ :source="source"
+ :risk-list="riskList"
+ />
+ </div>
+ </div>
+</template>
+
+<script lang="ts" setup>
+import { computed, watch } from "vue";
+import { groupBy } from "lodash-es";
+
+import RiskNavigation from "./RiskNavigation";
+import RiskSection from "./RiskSection.vue";
+import { useRiskCenterContext } from "./context";
+import { Risk, Risk_Source } from "@/types/proto/v1/risk_service";
+import { PresetRiskLevelList, SupportedSourceList } from "@/types";
+import { useRiskStore } from "@/store";
+import { orderByLevelDesc } from "./common";
+
+const riskStore = useRiskStore();
+const context = useRiskCenterContext();
+const { allowAdmin, navigation } = context;
+
+const filteredRiskList = computed(() => {
+ let list = [...riskStore.riskList];
+ const { source, levels } = navigation.value;
+ const search = navigation.value.search.trim();
+ // Risk_Source.SOURCE_UNSPECIFIED to "ALL"
+ if (source !== Risk_Source.SOURCE_UNSPECIFIED) {
+ list = list.filter((risk) => risk.source === source);
+ }
+ // empty to "ALL"
+ if (levels.size > 0) {
+ list = list.filter((risk) => levels.has(risk.level));
+ }
+ if (search) {
+ list = list.filter((risk) => risk.title.includes(search));
+ }
+ return list;
+});
+
+const riskListGroupBySource = computed(() => {
+ const groupBySource = groupBy(filteredRiskList.value, (risk) => risk.source);
+ const groups = SupportedSourceList.map((source) => {
+ const riskList = groupBySource[source] ?? [];
+ riskList.sort(orderByLevelDesc);
+ return { source, riskList };
+ });
+ if (navigation.value.source === Risk_Source.SOURCE_UNSPECIFIED) {
+ // Show "ALL" sources
+ return groups;
+ }
+
+ return groups.filter((group) => {
+ return (
+ group.riskList.length > 0 || group.source === navigation.value.source
+ );
+ });
+});
+
+const addRisk = () => {
+ const risk = Risk.fromJSON({
+ level: PresetRiskLevelList[0].level,
+ source: navigation.value.source || SupportedSourceList[0],
+ active: true,
+ });
+ context.dialog.value = {
+ mode: "CREATE",
+ risk,
+ };
+};
+
+watch(
+ context.dialog,
+ (dialog) => {
+ const source = dialog?.risk?.source;
+ if (!source) return;
+ if (navigation.value.source !== Risk_Source.SOURCE_UNSPECIFIED) {
+ navigation.value.source = source;
+ }
+ },
+ { immediate: true }
+);
+</script>
diff --git a/frontend/src/components/CustomApproval/Settings/components/RiskCenter/RiskDialog/RiskDialog.vue b/frontend/src/components/CustomApproval/Settings/components/RiskCenter/RiskDialog/RiskDialog.vue
new file mode 100644
index 0000000000..f71a4b1f60
--- /dev/null
+++ b/frontend/src/components/CustomApproval/Settings/components/RiskCenter/RiskDialog/RiskDialog.vue
@@ -0,0 +1,122 @@
+<template>
+ <BBModal
+ v-if="dialog"
+ :title="title"
+ :esc-closable="false"
+ :before-close="beforeClose"
+ :data-state-dirty="state.dirty"
+ @close="dialog = undefined"
+ >
+ <RiskForm
+ :dirty="state.dirty"
+ @cancel="cancel"
+ @update="state.dirty = true"
+ @save="handleSave"
+ />
+ <div
+ v-if="state.loading"
+ class="absolute inset-0 flex flex-col items-center justify-center bg-white/50 rounded-lg"
+ >
+ <BBSpin />
+ </div>
+ </BBModal>
+</template>
+
+<script lang="ts" setup>
+import { computed, reactive, watch } from "vue";
+import { useI18n } from "vue-i18n";
+import { useDialog } from "naive-ui";
+
+import { defer } from "@/utils";
+import { useRiskCenterContext } from "../context";
+import { sourceText } from "../common";
+import RiskForm from "./RiskForm.vue";
+import { Risk } from "@/types/proto/v1/risk_service";
+import { pushNotification, useRiskStore } from "@/store";
+
+type LocalState = {
+ loading: boolean;
+ dirty: boolean;
+};
+
+const { t } = useI18n();
+const context = useRiskCenterContext();
+const { allowAdmin, dialog } = context;
+const nDialog = useDialog();
+
+const state = reactive<LocalState>({
+ loading: false,
+ dirty: false,
+});
+
+const title = computed(() => {
+ const parts: string[] = [];
+ if (dialog.value) {
+ const { mode, risk } = dialog.value;
+ if (!allowAdmin.value) {
+ parts.push(t("custom-approval.security-rule.view-rule"));
+ } else {
+ if (mode === "CREATE") {
+ parts.push(t("custom-approval.security-rule.add-rule"));
+ } else if (mode === "EDIT") {
+ parts.push(t("custom-approval.security-rule.edit-rule"));
+ }
+ }
+ parts.push(sourceText(risk.source));
+ }
+ return parts.join(" - ");
+});
+const cancel = async () => {
+ const pass = await beforeClose();
+ if (pass) {
+ dialog.value = undefined;
+ }
+};
+
+const beforeClose = async () => {
+ if (!state.dirty) {
+ return true;
+ }
+ if (!allowAdmin.value) {
+ return true;
+ }
+ const d = defer<boolean>();
+ nDialog.info({
+ title: t("common.close"),
+ content: t("common.will-lose-unsaved-data"),
+ maskClosable: false,
+ closeOnEsc: false,
+ positiveText: t("common.confirm"),
+ negativeText: t("common.cancel"),
+ onPositiveClick: () => d.resolve(true),
+ onNegativeClick: () => d.resolve(false),
+ });
+ return d.promise;
+};
+
+const handleSave = async (risk: Risk) => {
+ state.loading = true;
+
+ try {
+ await useRiskStore().upsertRisk(risk);
+
+ state.dirty = false;
+ pushNotification({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t("common.updated"),
+ });
+ dialog.value = undefined;
+ } finally {
+ state.loading = false;
+ }
+};
+
+watch(
+ dialog,
+ () => {
+ state.dirty = false;
+ },
+ { immediate: true }
+);
+</script>
diff --git a/frontend/src/components/CustomApproval/Settings/components/RiskCenter/RiskDialog/RiskForm.vue b/frontend/src/components/CustomApproval/Settings/components/RiskCenter/RiskDialog/RiskForm.vue
new file mode 100644
index 0000000000..4691e5a18d
--- /dev/null
+++ b/frontend/src/components/CustomApproval/Settings/components/RiskCenter/RiskDialog/RiskForm.vue
@@ -0,0 +1,179 @@
+<template>
+ <div
+ class="w-[calc(100vw-8rem)] lg:max-w-[75vw] 2xl:max-w-[55vw] max-h-[calc(100vh-10rem)] flex flex-col"
+ >
+ <div class="flex-1 flex flex-col divide-y overflow-hidden">
+ <div class="flex items-start gap-x-4 mb-4">
+ <div class="space-y-2 flex-1">
+ <label class="block font-medium text-sm text-control">
+ {{ $t("common.name") }}
+ </label>
+ <NInput
+ v-model:value="state.risk.title"
+ :disabled="!allowAdmin"
+ :placeholder="$t('custom-approval.security-rule.input-rule-name')"
+ @input="$emit('update')"
+ />
+ </div>
+ <div class="space-y-2">
+ <label class="block font-medium text-sm text-control">
+ {{ $t("custom-approval.security-rule.risk.self") }}
+ </label>
+ <RiskLevelSelect
+ v-model:value="state.risk.level"
+ :disabled="!allowAdmin"
+ @update:value="$emit('update')"
+ />
+ </div>
+ <div class="space-y-2">
+ <label class="block font-medium text-sm text-control">
+ {{ $t("custom-approval.security-rule.source.self") }}
+ </label>
+ <RiskSourceSelect
+ v-model:value="state.risk.source"
+ :disabled="mode === 'EDIT' || !allowAdmin"
+ @update:value="$emit('update')"
+ />
+ </div>
+ </div>
+
+ <div class="flex-1 flex items-stretch gap-x-4 overflow-hidden">
+ <div class="flex-1 space-y-2 py-4 overflow-x-hidden overflow-y-auto">
+ <h3 class="font-medium text-sm text-control">
+ {{ $t("custom-approval.security-rule.condition.self") }}
+ </h3>
+ <div class="text-sm text-control-light">
+ {{ $t("custom-approval.security-rule.condition.description-tips") }}
+ <LearnMoreLink url="https://www.bytebase.com/404" class="ml-1" />
+ </div>
+ <ExprEditor
+ :expr="state.expr"
+ :allow-admin="allowAdmin"
+ :allow-high-level-factors="false"
+ :risk-source="state.risk.source"
+ @update="$emit('update')"
+ />
+ </div>
+
+ <div
+ v-if="allowAdmin"
+ class="w-[45%] max-w-[40rem] overflow-y-auto py-4 shrink-0"
+ >
+ <h3 class="font-medium text-sm text-control mb-2">
+ {{ $t("custom-approval.security-rule.template.templates") }}
+ </h3>
+ <RuleTemplateTable
+ :dirty="dirty"
+ @apply-template="handleApplyRuleTemplate"
+ />
+ </div>
+ </div>
+ </div>
+ <footer
+ v-if="allowAdmin"
+ class="flex items-center justify-end gap-x-2 pt-4 border-t"
+ >
+ <NButton @click="$emit('cancel')">{{ $t("common.cancel") }}</NButton>
+ <NButton
+ type="primary"
+ :disabled="!allowCreateOrUpdate"
+ @click="handleUpsert"
+ >
+ {{ mode === "CREATE" ? $t("common.add") : $t("common.update") }}
+ </NButton>
+ </footer>
+ </div>
+</template>
+
+<script lang="ts" setup>
+import { computed, ref } from "vue";
+import { NButton, NInput } from "naive-ui";
+import { cloneDeep } from "lodash-es";
+
+import type { Risk } from "@/types/proto/v1/risk_service";
+import {
+ Expr as CELExpr,
+ ParsedExpr,
+} from "@/types/proto/google/api/expr/v1alpha1/syntax";
+import type { ConditionGroupExpr } from "@/plugins/cel";
+import { useRiskCenterContext } from "../context";
+import LearnMoreLink from "@/components/LearnMoreLink.vue";
+import RiskLevelSelect from "./RiskLevelSelect.vue";
+import RiskSourceSelect from "./RiskSourceSelect.vue";
+import ExprEditor from "../../common/ExprEditor";
+import RuleTemplateTable from "./RuleTemplateTable.vue";
+import {
+ resolveCELExpr,
+ buildCELExpr,
+ wrapAsGroup,
+ validateSimpleExpr,
+} from "@/plugins/cel";
+
+type LocalState = {
+ risk: Risk;
+ expr: ConditionGroupExpr;
+};
+
+const props = defineProps<{
+ dirty?: boolean;
+}>();
+
+const emit = defineEmits<{
+ (event: "cancel"): void;
+ (event: "update"): void;
+ (event: "save", risk: Risk): void;
+}>();
+
+const context = useRiskCenterContext();
+const { allowAdmin } = context;
+
+const mode = computed(() => context.dialog.value!.mode);
+
+const resolveLocalState = (): LocalState => {
+ const risk = cloneDeep(context.dialog.value!.risk);
+ return {
+ risk,
+ expr: wrapAsGroup(
+ resolveCELExpr(risk.expression?.expr ?? CELExpr.fromJSON({}))
+ ),
+ };
+};
+
+const state = ref(resolveLocalState());
+
+const allowCreateOrUpdate = computed(() => {
+ if (mode.value === "EDIT") {
+ if (!props.dirty) return false;
+ }
+
+ const { risk, expr } = state.value;
+ if (!risk.title.trim()) return false;
+
+ if (!validateSimpleExpr(expr)) {
+ return false;
+ }
+
+ return true;
+});
+
+const handleUpsert = async () => {
+ if (!context.hasFeature.value) {
+ context.showFeatureModal.value = true;
+ return;
+ }
+ const risk = cloneDeep(state.value.risk);
+ risk.expression = ParsedExpr.fromJSON({
+ expr: buildCELExpr(state.value.expr),
+ });
+ emit("save", risk);
+};
+
+const handleApplyRuleTemplate = (
+ overrides: Partial<Risk>,
+ expr: ConditionGroupExpr
+) => {
+ Object.assign(state.value.risk, overrides);
+ state.value.expr = cloneDeep(expr);
+ emit("update");
+};
+</script>
diff --git a/frontend/src/components/CustomApproval/Settings/components/RiskCenter/RiskDialog/RiskLevelSelect.vue b/frontend/src/components/CustomApproval/Settings/components/RiskCenter/RiskDialog/RiskLevelSelect.vue
new file mode 100644
index 0000000000..cbc8e56a7c
--- /dev/null
+++ b/frontend/src/components/CustomApproval/Settings/components/RiskCenter/RiskDialog/RiskLevelSelect.vue
@@ -0,0 +1,41 @@
+<template>
+ <NSelect
+ style="width: 8rem"
+ :value="value"
+ :options="options"
+ :placeholder="$t('custom-approval.security-rule.risk.select')"
+ :consistent-menu-width="false"
+ :disabled="disabled || !allowAdmin"
+ @update:value="$emit('update:value', $event)"
+ />
+</template>
+
+<script lang="ts" setup>
+import { computed } from "vue";
+import { NSelect, SelectOption, type SelectProps } from "naive-ui";
+
+import { PresetRiskLevelList } from "@/types";
+import { useRiskCenterContext } from "../context";
+import { levelText } from "../common";
+
+export interface RiskLevelSelectorProps extends SelectProps {
+ value: number;
+ disabled?: boolean;
+}
+
+defineProps<RiskLevelSelectorProps>();
+
+defineEmits<{
+ (event: "update:value", value: string | undefined): void;
+}>();
+
+const context = useRiskCenterContext();
+const { allowAdmin } = context;
+
+const options = computed(() => {
+ return PresetRiskLevelList.map<SelectOption>(({ level }) => ({
+ label: levelText(level),
+ value: level,
+ }));
+});
+</script>
diff --git a/frontend/src/components/CustomApproval/Settings/components/RiskCenter/RiskDialog/RiskSourceSelect.vue b/frontend/src/components/CustomApproval/Settings/components/RiskCenter/RiskDialog/RiskSourceSelect.vue
new file mode 100644
index 0000000000..388e895ac1
--- /dev/null
+++ b/frontend/src/components/CustomApproval/Settings/components/RiskCenter/RiskDialog/RiskSourceSelect.vue
@@ -0,0 +1,42 @@
+<template>
+ <NSelect
+ style="width: 11rem"
+ :value="value"
+ :options="options"
+ :placeholder="$t('custom-approval.security-rule.source.select')"
+ :consistent-menu-width="false"
+ :disabled="disabled || !allowAdmin"
+ @update:value="$emit('update:value', $event)"
+ />
+</template>
+
+<script lang="ts" setup>
+import { computed } from "vue";
+import { NSelect, SelectOption, type SelectProps } from "naive-ui";
+
+import { Risk_Source } from "@/types/proto/v1/risk_service";
+import { SupportedSourceList } from "@/types";
+import { useRiskCenterContext } from "../context";
+import { sourceText } from "../common";
+
+export interface RiskSourceSelectProps extends SelectProps {
+ value: Risk_Source;
+ disabled?: boolean;
+}
+
+defineProps<RiskSourceSelectProps>();
+
+defineEmits<{
+ (event: "update:value", source: Risk_Source | undefined): void;
+}>();
+
+const context = useRiskCenterContext();
+const { allowAdmin } = context;
+
+const options = computed(() => {
+ return SupportedSourceList.map<SelectOption>((source) => ({
+ label: sourceText(source),
+ value: source,
+ }));
+});
+</script>
diff --git a/frontend/src/components/CustomApproval/Settings/components/RiskCenter/RiskDialog/RuleTemplateTable.vue b/frontend/src/components/CustomApproval/Settings/components/RiskCenter/RiskDialog/RuleTemplateTable.vue
new file mode 100644
index 0000000000..8f803bfef7
--- /dev/null
+++ b/frontend/src/components/CustomApproval/Settings/components/RiskCenter/RiskDialog/RuleTemplateTable.vue
@@ -0,0 +1,138 @@
+<template>
+ <BBGrid
+ class="border"
+ :column-list="COLUMNS"
+ :data-source="filteredTemplateList"
+ :row-clickable="false"
+ row-key="key"
+ >
+ <template #item="{ item: tpl }: { item: RuleTemplate }">
+ <div class="bb-grid-cell !pl-2 !pr-1">
+ {{ titleOfTemplate(tpl) }}
+ </div>
+ <div class="bb-grid-cell gap-x-1 !pl-1 !pr-2">
+ <NButton size="tiny" @click="applyTemplate(tpl)">
+ {{ $t("custom-approval.security-rule.template.load") }}
+ </NButton>
+ <NButton size="tiny" @click="viewTemplate = tpl">
+ {{ $t("common.view") }}
+ </NButton>
+ </div>
+ </template>
+ </BBGrid>
+
+ <BBModal
+ v-if="viewTemplate"
+ :title="$t('custom-approval.security-rule.template.view')"
+ class="!w-auto lg:!max-w-[36rem]"
+ @close="viewTemplate = undefined"
+ >
+ <ViewTemplate :template="viewTemplate" />
+ </BBModal>
+</template>
+
+<script lang="ts" setup>
+import { computed, ref } from "vue";
+import { useI18n } from "vue-i18n";
+import { NButton, useDialog } from "naive-ui";
+
+import { BBGrid, type BBGridColumn } from "@/bbkit";
+import {
+ type RuleTemplate,
+ useRuleTemplates,
+ titleOfTemplate,
+} from "./template";
+import { useRiskCenterContext } from "../context";
+import { defer } from "@/utils";
+import { Risk, Risk_Source } from "@/types/proto/v1/risk_service";
+import { buildCELExpr, ConditionGroupExpr } from "@/plugins/cel";
+import { ParsedExpr } from "@/types/proto/google/api/expr/v1alpha1/syntax";
+import ViewTemplate from "./ViewTemplate.vue";
+
+const props = defineProps<{
+ dirty?: boolean;
+}>();
+
+const emit = defineEmits<{
+ (
+ event: "apply-template",
+ overrides: Partial<Risk>,
+ expr: ConditionGroupExpr
+ ): void;
+}>();
+
+const { t } = useI18n();
+const { dialog } = useRiskCenterContext();
+const templateList = useRuleTemplates();
+const viewTemplate = ref<RuleTemplate>();
+const nDialog = useDialog();
+
+const COLUMNS = computed(() => {
+ const columns: BBGridColumn[] = [
+ {
+ title: t("custom-approval.security-rule.rule-name"),
+ width: "1fr",
+ class: "!pl-2 !pr-1 !py-0.5",
+ },
+ {
+ title: t("common.operations"),
+ width: "auto",
+ class: "!px-1",
+ },
+ ];
+ return columns;
+});
+
+const filteredTemplateList = computed(() => {
+ let list = [...templateList.value];
+ const { mode, risk } = dialog.value!;
+ if (mode === "EDIT") {
+ const { source } = risk;
+ list = list.filter((tpl) => {
+ return (
+ tpl.source === Risk_Source.SOURCE_UNSPECIFIED || tpl.source === source
+ );
+ });
+ }
+ return list;
+});
+
+const confirmApplyTemplate = async () => {
+ if (dialog.value?.mode === "CREATE" && !props.dirty) {
+ return true;
+ }
+ const d = defer<boolean>();
+ nDialog.warning({
+ title: t("custom-approval.security-rule.template.load-template"),
+ content: t("common.will-override-current-data"),
+ maskClosable: false,
+ closeOnEsc: false,
+ positiveText: t("common.confirm"),
+ negativeText: t("common.cancel"),
+ onPositiveClick: () => d.resolve(true),
+ onNegativeClick: () => d.resolve(false),
+ });
+ return d.promise;
+};
+
+const applyTemplate = async (template: RuleTemplate) => {
+ if (!(await confirmApplyTemplate())) {
+ return;
+ }
+
+ const { expr, source, level } = template;
+ const title = titleOfTemplate(template);
+ const { mode } = dialog.value!;
+ const overrides: Partial<Risk> = {
+ expression: ParsedExpr.fromJSON({
+ expr: buildCELExpr(expr),
+ }),
+ level,
+ title,
+ };
+ if (mode === "CREATE" && source !== Risk_Source.SOURCE_UNSPECIFIED) {
+ overrides.source = source;
+ }
+ emit("apply-template", overrides, expr);
+};
+</script>
diff --git a/frontend/src/components/CustomApproval/Settings/components/RiskCenter/RiskDialog/ViewTemplate.vue b/frontend/src/components/CustomApproval/Settings/components/RiskCenter/RiskDialog/ViewTemplate.vue
new file mode 100644
index 0000000000..28f7775878
--- /dev/null
+++ b/frontend/src/components/CustomApproval/Settings/components/RiskCenter/RiskDialog/ViewTemplate.vue
@@ -0,0 +1,38 @@
+<template>
+ <ExprEditor
+ :expr="template.expr"
+ :risk-source="source"
+ :allow-admin="false"
+ :allow-high-level-factors="false"
+ />
+</template>
+
+<script lang="ts" setup>
+import { computed, h } from "vue";
+
+import { useOverrideSubtitle } from "@/bbkit/BBModal.vue";
+import { Risk_Source } from "@/types/proto/v1/risk_service";
+import { ExprEditor } from "../../common";
+import { type RuleTemplate, titleOfTemplate } from "./template";
+
+const props = defineProps<{
+ template: RuleTemplate;
+}>();
+
+useOverrideSubtitle(() => {
+ return h(
+ "div",
+ {
+ class:
+ "text-xs text-control-light mt-1 whitespace-pre-wrap overflow-hidden",
+ },
+ titleOfTemplate(props.template)
+ );
+});
+
+const source = computed(() => {
+ const { source } = props.template;
+ if (source === Risk_Source.SOURCE_UNSPECIFIED) return Risk_Source.DDL;
+ return source;
+});
+</script>
diff --git a/frontend/src/components/CustomApproval/Settings/components/RiskCenter/RiskDialog/index.ts b/frontend/src/components/CustomApproval/Settings/components/RiskCenter/RiskDialog/index.ts
new file mode 100644
index 0000000000..5297ceb192
--- /dev/null
+++ b/frontend/src/components/CustomApproval/Settings/components/RiskCenter/RiskDialog/index.ts
@@ -0,0 +1,3 @@
+import RiskDialog from "./RiskDialog.vue";
+
+export default RiskDialog;
diff --git a/frontend/src/components/CustomApproval/Settings/components/RiskCenter/RiskDialog/template.ts b/frontend/src/components/CustomApproval/Settings/components/RiskCenter/RiskDialog/template.ts
new file mode 100644
index 0000000000..8de451e583
--- /dev/null
+++ b/frontend/src/components/CustomApproval/Settings/components/RiskCenter/RiskDialog/template.ts
@@ -0,0 +1,120 @@
+import { computed } from "vue";
+import { first, last } from "lodash-es";
+
+import { ConditionGroupExpr, wrapAsGroup } from "@/plugins/cel";
+import { useEnvironmentList } from "@/store";
+import { PresetRiskLevel } from "@/types";
+import { Risk_Source } from "@/types/proto/v1/risk_service";
+import { t, te } from "@/plugins/i18n";
+
+/*
+
+The risk for the production environment is considered to be high.
+生产环境,默认为高风险。
+environment == "prod"
+
+The risk value for the development environment is considered to be low.
+开发环境,默认为低风险
+environment == "dev"
+
+In the production environment, if the number of rows to be updated or deleted exceeds 10000, the risk is considered to be high.
+生产环境中更新或删除的数据行数超过 100000,默认为高风险。
+environment == "prod" & affected_rows > 10000 & sql_type in ["UPDATE", "DELETE"]
+
+Creating a database in the production environment is considered to be a moderate risk.
+在生产环境中创建数据库,默认为中风险。
+environment == "prod"
+*/
+
+export type RuleTemplate = {
+ key: string;
+ expr: ConditionGroupExpr;
+ level: number;
+ source: Risk_Source;
+};
+
+export const useRuleTemplates = () => {
+ const environmentList = useEnvironmentList();
+ const dev = computed(() => first(environmentList.value));
+ const prod = computed(() => last(environmentList.value));
+
+ const ruleTemplateList = computed(() => {
+ const templates: RuleTemplate[] = [];
+ if (prod.value) {
+ // environment == "prod" -> HIGH
+ templates.push({
+ key: "environment-prod-high",
+ expr: wrapAsGroup({
+ operator: "_==_",
+ args: ["environment_id", prod.value.resourceId],
+ }),
+ level: PresetRiskLevel.HIGH,
+ source: Risk_Source.SOURCE_UNSPECIFIED,
+ });
+ }
+ if (dev.value) {
+ // environment == "dev" -> LOW
+ templates.push({
+ key: "environment-dev-low",
+ expr: wrapAsGroup({
+ operator: "_==_",
+ args: ["environment_id", dev.value.resourceId],
+ }),
+ level: PresetRiskLevel.LOW,
+ source: Risk_Source.SOURCE_UNSPECIFIED,
+ });
+ }
+ if (prod.value) {
+ // environment == "prod" && affected_rows > 10000 && sql_type in ["UPDATE", "DELETE"]
+ // -> HIGH
+ templates.push({
+ key: "dml-in-environment-prod-10k-rows-high",
+ expr: wrapAsGroup({
+ operator: "_&&_",
+ args: [
+ {
+ operator: "_==_",
+ args: ["environment_id", prod.value.resourceId],
+ },
+ {
+ operator: "_>_",
+ args: ["affected_rows", 10000],
+ },
+ {
+ operator: "@in",
+ args: ["sql_type", ["UPDATE", "DELETE"]],
+ },
+ ],
+ }),
+ level: PresetRiskLevel.HIGH,
+ source: Risk_Source.DML,
+ });
+ }
+ if (prod.value) {
+ // create database
+ // environment == "prod"
+ // -> MODERATE
+ templates.push({
+ key: "create-database-in-environment-prod-moderate",
+ expr: wrapAsGroup({
+ operator: "_==_",
+ args: ["environment_id", prod.value.resourceId],
+ }),
+ level: PresetRiskLevel.MODERATE,
+ source: Risk_Source.CREATE_DATABASE,
+ });
+ }
+ return templates;
+ });
+
+ return ruleTemplateList;
+};
+
+export const titleOfTemplate = (template: RuleTemplate) => {
+ const { key } = template;
+ const keypath = `custom-approval.security-rule.template.presets.${key}`;
+ if (te(keypath)) {
+ return t(keypath);
+ }
+ return key;
+};
diff --git a/frontend/src/components/CustomApproval/Settings/components/RiskCenter/RiskNavigation/RiskLevelFilter.vue b/frontend/src/components/CustomApproval/Settings/components/RiskCenter/RiskNavigation/RiskLevelFilter.vue
new file mode 100644
index 0000000000..a532b04b0a
--- /dev/null
+++ b/frontend/src/components/CustomApproval/Settings/components/RiskCenter/RiskNavigation/RiskLevelFilter.vue
@@ -0,0 +1,67 @@
+<template>
+ <div class="flex items-center gap-x-3">
+ <label
+ v-for="item in riskLevelFilterItemList"
+ :key="item.value"
+ class="flex items-center gap-x-2 text-sm text-gray-600"
+ >
+ <NCheckbox
+ :checked="isCheckedLevel(item.value)"
+ @update:checked="toggleCheckLevel(item.value, $event)"
+ >
+ <BBBadge
+ class="whitespace-nowrap"
+ :text="item.label"
+ :can-remove="false"
+ :style="item.style"
+ size="small"
+ />
+ </NCheckbox>
+ </label>
+ </div>
+</template>
+
+<script lang="ts" setup>
+import { computed } from "vue";
+import { NCheckbox } from "naive-ui";
+
+import BBBadge, { type BBBadgeStyle } from "@/bbkit/BBBadge.vue";
+import { PresetRiskLevel, PresetRiskLevelList } from "@/types";
+import { useRiskCenterContext } from "../context";
+import { levelText } from "../common";
+
+type RiskLevelFilterItem = {
+ value: number;
+ label: string;
+ style: BBBadgeStyle;
+};
+
+const { navigation } = useRiskCenterContext();
+
+const riskLevelFilterItemList = computed(() => {
+ return PresetRiskLevelList.map<RiskLevelFilterItem>(({ level }) => {
+ return {
+ value: level,
+ label: levelText(level),
+ style:
+ level === PresetRiskLevel.HIGH
+ ? "CRITICAL"
+ : level === PresetRiskLevel.MODERATE
+ ? "WARN"
+ : level === PresetRiskLevel.LOW
+ ? "INFO"
+ : "DISABLED",
+ };
+ });
+});
+
+const isCheckedLevel = (level: number) => {
+ return navigation.value.levels.has(level);
+};
+
+const toggleCheckLevel = (level: number, checked: boolean) => {
+ const { levels } = navigation.value;
+ if (checked) levels.add(level);
+ else levels.delete(level);
+};
+</script>
diff --git a/frontend/src/components/CustomApproval/Settings/components/RiskCenter/RiskNavigation/RiskNavigation.vue b/frontend/src/components/CustomApproval/Settings/components/RiskCenter/RiskNavigation/RiskNavigation.vue
new file mode 100644
index 0000000000..f824d19691
--- /dev/null
+++ b/frontend/src/components/CustomApproval/Settings/components/RiskCenter/RiskNavigation/RiskNavigation.vue
@@ -0,0 +1,35 @@
+<template>
+ <div class="space-y-2">
+ <div class="flex items-center justify-between">
+ <RiskLevelFilter />
+
+ <div class="flex items-center justify-end gap-x-4">
+ <NInput
+ v-model:value="navigation.search"
+ :clearable="true"
+ :placeholder="$t('custom-approval.security-rule.search')"
+ >
+ <template #prefix>
+ <heroicons:magnifying-glass class="w-4 h-4" />
+ </template>
+ </NInput>
+
+ <slot name="suffix" />
+ </div>
+ </div>
+
+ <div class="flex items-center justify-start">
+ <RiskSourceFilter />
+ </div>
+ </div>
+</template>
+
+<script lang="ts" setup>
+import { NInput } from "naive-ui";
+
+import RiskSourceFilter from "./RiskSourceFilter.vue";
+import RiskLevelFilter from "./RiskLevelFilter.vue";
+import { useRiskCenterContext } from "../context";
+
+const { navigation } = useRiskCenterContext();
+</script>
diff --git a/frontend/src/components/CustomApproval/Settings/components/RiskCenter/RiskNavigation/RiskSourceFilter.vue b/frontend/src/components/CustomApproval/Settings/components/RiskCenter/RiskNavigation/RiskSourceFilter.vue
new file mode 100644
index 0000000000..c779b07e58
--- /dev/null
+++ b/frontend/src/components/CustomApproval/Settings/components/RiskCenter/RiskNavigation/RiskSourceFilter.vue
@@ -0,0 +1,66 @@
+<template>
+ <BBTabFilter
+ :tab-item-list="tabItemList"
+ :selected-index="index"
+ @select-index="index = $event"
+ />
+</template>
+
+<script lang="ts" setup>
+import { computed } from "vue";
+import { useI18n } from "vue-i18n";
+
+import { BBTabFilter, type BBTabFilterItem } from "@/bbkit";
+import { Risk_Source } from "@/types/proto/v1/risk_service";
+import { useRiskCenterContext } from "../context";
+import { SupportedSourceList } from "@/types";
+import { minmax } from "@/utils";
+import { sourceText } from "../common";
+
+export interface RiskSourceFilterItem {
+ value: Risk_Source;
+ label: string;
+}
+
+const context = useRiskCenterContext();
+const { navigation } = context;
+
+const { t } = useI18n();
+
+const filterItemList = computed(() => {
+ const items: RiskSourceFilterItem[] = [
+ {
+ value: Risk_Source.SOURCE_UNSPECIFIED,
+ label: t("common.all"),
+ },
+ ];
+ SupportedSourceList.forEach((source) => {
+ items.push({
+ value: source,
+ label: sourceText(source),
+ });
+ });
+ return items;
+});
+
+const index = computed({
+ get() {
+ const index = filterItemList.value.findIndex(
+ (item) => item.value === navigation.value.source
+ );
+ if (index < 0) return 0;
+ return index;
+ },
+ set(index) {
+ index = minmax(index, 0, filterItemList.value.length - 1);
+ navigation.value.source = filterItemList.value[index].value;
+ },
+});
+
+const tabItemList = computed(() => {
+ return filterItemList.value.map<BBTabFilterItem>((item) => ({
+ title: item.label,
+ alert: false,
+ }));
+});
+</script>
diff --git a/frontend/src/components/CustomApproval/Settings/components/RiskCenter/RiskNavigation/index.ts b/frontend/src/components/CustomApproval/Settings/components/RiskCenter/RiskNavigation/index.ts
new file mode 100644
index 0000000000..4caeaaaedb
--- /dev/null
+++ b/frontend/src/components/CustomApproval/Settings/components/RiskCenter/RiskNavigation/index.ts
@@ -0,0 +1,3 @@
+import RiskNavigation from "./RiskNavigation.vue";
+
+export default RiskNavigation;
diff --git a/frontend/src/components/CustomApproval/Settings/components/RiskCenter/RiskSection.vue b/frontend/src/components/CustomApproval/Settings/components/RiskCenter/RiskSection.vue
new file mode 100644
index 0000000000..fe9dfb4430
--- /dev/null
+++ b/frontend/src/components/CustomApproval/Settings/components/RiskCenter/RiskSection.vue
@@ -0,0 +1,24 @@
+<template>
+ <div class="space-y-2">
+ <div class="flex items-center justify-start">
+ <div class="font-medium text-base">
+ {{ sourceText(source) }}
+ </div>
+ <div class="ml-1">({{ riskList.length }})</div>
+ </div>
+ <div>
+ <RiskTable :risk-list="riskList" />
+ </div>
+ </div>
+</template>
+
+<script lang="ts" setup>
+import RiskTable from "./RiskTable.vue";
+import { Risk, Risk_Source } from "@/types/proto/v1/risk_service";
+import { sourceText } from "./common";
+
+defineProps<{
+ source: Risk_Source;
+ riskList: Risk[];
+}>();
+</script>
diff --git a/frontend/src/components/CustomApproval/Settings/components/RiskCenter/RiskTable.vue b/frontend/src/components/CustomApproval/Settings/components/RiskCenter/RiskTable.vue
new file mode 100644
index 0000000000..1158d3d5dd
--- /dev/null
+++ b/frontend/src/components/CustomApproval/Settings/components/RiskCenter/RiskTable.vue
@@ -0,0 +1,109 @@
+<template>
+ <BBGrid
+ :column-list="COLUMN_LIST"
+ :data-source="riskList"
+ :row-clickable="false"
+ :show-placeholder="true"
+ row-key="name"
+ class="border"
+ >
+ <template #item="{ item: risk }: { item: Risk }">
+ <div class="bb-grid-cell justify-center">
+ {{ levelText(risk.level) }}
+ </div>
+ <div class="bb-grid-cell">
+ {{ risk.title }}
+ </div>
+ <div class="bb-grid-cell justify-center">
+ <SpinnerSwitch
+ :value="risk.active"
+ :disabled="!allowAdmin"
+ :on-toggle="(active) => toggleRisk(risk, active)"
+ size="small"
+ />
+ </div>
+ <div class="bb-grid-cell gap-x-2">
+ <NButton size="small" @click="editRisk(risk)">
+ {{ allowAdmin ? $t("common.edit") : $t("common.view") }}
+ </NButton>
+ <SpinnerButton
+ size="small"
+ :tooltip="$t('custom-approval.security-rule.delete')"
+ :disabled="!allowAdmin"
+ :on-confirm="() => deleteRisk(risk)"
+ >
+ {{ $t("common.delete") }}
+ </SpinnerButton>
+ </div>
+ </template>
+ </BBGrid>
+</template>
+
+<script lang="ts" setup>
+import { computed } from "vue";
+import { useI18n } from "vue-i18n";
+import { NButton } from "naive-ui";
+
+import { BBGrid, type BBGridColumn } from "@/bbkit";
+import { SpinnerButton, SpinnerSwitch } from "../common";
+import { useRiskCenterContext } from "./context";
+import { Risk } from "@/types/proto/v1/risk_service";
+import { pushNotification, useRiskStore } from "@/store";
+import { levelText } from "./common";
+
+defineProps<{
+ riskList: Risk[];
+}>();
+
+const { t } = useI18n();
+const context = useRiskCenterContext();
+const { allowAdmin } = context;
+
+const COLUMN_LIST = computed(() => {
+ const columns: BBGridColumn[] = [
+ {
+ title: t("custom-approval.security-rule.risk.self"),
+ width: "8rem",
+ class: "justify-center",
+ },
+ { title: t("common.name"), width: "1fr" },
+ {
+ title: t("custom-approval.security-rule.active"),
+ width: "6rem",
+ class: "justify-center",
+ },
+ {
+ title: t("common.operations"),
+ width: "10rem",
+ },
+ ];
+
+ return columns;
+});
+
+const editRisk = (risk: Risk) => {
+ context.dialog.value = {
+ mode: "EDIT",
+ risk,
+ };
+};
+
+const toggleRisk = async (risk: Risk, active: boolean) => {
+ risk.active = active;
+ await useRiskStore().upsertRisk(risk);
+ pushNotification({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t("common.updated"),
+ });
+};
+
+const deleteRisk = async (risk: Risk) => {
+ await useRiskStore().deleteRisk(risk);
+ pushNotification({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t("common.deleted"),
+ });
+};
+</script>
diff --git a/frontend/src/components/CustomApproval/Settings/components/RiskCenter/common.ts b/frontend/src/components/CustomApproval/Settings/components/RiskCenter/common.ts
new file mode 100644
index 0000000000..ffdedd32fe
--- /dev/null
+++ b/frontend/src/components/CustomApproval/Settings/components/RiskCenter/common.ts
@@ -0,0 +1,31 @@
+import {
+ Risk,
+ Risk_Source,
+ risk_SourceToJSON,
+} from "@/types/proto/v1/risk_service";
+import { useI18n } from "vue-i18n";
+
+export const sourceText = (source: Risk_Source) => {
+ const { t, te } = useI18n();
+ const name = risk_SourceToJSON(source);
+ const keypath = `custom-approval.security-rule.risk.namespace.${name.toLowerCase()}`;
+ if (te(keypath)) {
+ return t(keypath);
+ }
+ return name;
+};
+
+export const levelText = (level: number) => {
+ const { t, te } = useI18n();
+ const keypath = `custom-approval.security-rule.risk.risk-level.${level}`;
+ if (te(keypath)) {
+ return t(keypath);
+ }
+ return String(level);
+};
+
+export const orderByLevelDesc = (a: Risk, b: Risk): number => {
+ if (a.level !== b.level) return -(a.level - b.level);
+ if (a.name === b.name) return 0;
+ return a.name < b.name ? -1 : 1;
+};
diff --git a/frontend/src/components/CustomApproval/Settings/components/RiskCenter/context.ts b/frontend/src/components/CustomApproval/Settings/components/RiskCenter/context.ts
new file mode 100644
index 0000000000..486393873b
--- /dev/null
+++ b/frontend/src/components/CustomApproval/Settings/components/RiskCenter/context.ts
@@ -0,0 +1,35 @@
+import { inject, provide, type InjectionKey, type Ref } from "vue";
+import { Risk, Risk_Source } from "@/types/proto/v1/risk_service";
+
+export type NavigationContext = {
+ source: Risk_Source;
+ levels: Set<number>; // empty to "ALL"
+ search: string; // Risk_Source.SOURCE_UNSPECIFIED to "ALL"
+};
+
+export type DialogContext = {
+ mode: "EDIT" | "CREATE";
+ risk: Risk;
+};
+
+export type RiskCenterContext = {
+ hasFeature: Ref<boolean>;
+ showFeatureModal: Ref<boolean>;
+ allowAdmin: Ref<boolean>;
+ ready: Ref<boolean>;
+
+ navigation: Ref<NavigationContext>;
+ dialog: Ref<DialogContext | undefined>;
+};
+
+export const KEY = Symbol(
+ "bb.settings.risk-center"
+) as InjectionKey<RiskCenterContext>;
+
+export const useRiskCenterContext = () => {
+ return inject(KEY)!;
+};
+
+export const provideRiskCenterContext = (context: RiskCenterContext) => {
+ provide(KEY, context);
+};
diff --git a/frontend/src/components/CustomApproval/Settings/components/RiskCenter/index.ts b/frontend/src/components/CustomApproval/Settings/components/RiskCenter/index.ts
new file mode 100644
index 0000000000..4fb77573c1
--- /dev/null
+++ b/frontend/src/components/CustomApproval/Settings/components/RiskCenter/index.ts
@@ -0,0 +1,6 @@
+import RiskCenter from "./RiskCenter.vue";
+import RiskDialog from "./RiskDialog";
+
+export * from "./context";
+export default RiskCenter;
+export { RiskCenter, RiskDialog };
diff --git a/frontend/src/components/CustomApproval/Settings/components/common/ExprEditor/Condition.vue b/frontend/src/components/CustomApproval/Settings/components/common/ExprEditor/Condition.vue
new file mode 100644
index 0000000000..496118bada
--- /dev/null
+++ b/frontend/src/components/CustomApproval/Settings/components/common/ExprEditor/Condition.vue
@@ -0,0 +1,52 @@
+<!-- eslint-disable vue/no-mutating-props -->
+
+<template>
+ <NInputGroup
+ class="bb-risk-expr-editor-condition w-full flex items-center overflow-x-hidden"
+ >
+ <FactorSelect :expr="expr" />
+
+ <OperatorSelect :expr="expr" />
+
+ <ValueInput :expr="expr" />
+
+ <NButton
+ v-if="allowAdmin"
+ size="small"
+ type="default"
+ :style="'flex-shrink: 0;padding-left: 0;padding-right: 0;--n-width: 28px;--n-color: white;'"
+ @click="$emit('remove')"
+ >
+ <heroicons:trash class="w-3.5 h-3.5" />
+ </NButton>
+ </NInputGroup>
+</template>
+
+<script lang="ts" setup>
+import { watch } from "vue";
+import { NButton, NInputGroup } from "naive-ui";
+
+import { type ConditionExpr } from "@/plugins/cel";
+import { FactorSelect, OperatorSelect, ValueInput } from "./components";
+import { useExprEditorContext } from "./context";
+
+const props = defineProps<{
+ expr: ConditionExpr;
+}>();
+
+const emit = defineEmits<{
+ (event: "remove"): void;
+ (event: "update"): void;
+}>();
+
+const context = useExprEditorContext();
+const { allowAdmin } = context;
+
+watch(
+ () => props.expr,
+ () => {
+ emit("update");
+ },
+ { deep: true }
+);
+</script>
diff --git a/frontend/src/components/CustomApproval/Settings/components/common/ExprEditor/ConditionGroup.vue b/frontend/src/components/CustomApproval/Settings/components/common/ExprEditor/ConditionGroup.vue
new file mode 100644
index 0000000000..95be4654bb
--- /dev/null
+++ b/frontend/src/components/CustomApproval/Settings/components/common/ExprEditor/ConditionGroup.vue
@@ -0,0 +1,196 @@
+<!-- eslint-disable vue/no-mutating-props -->
+
+<template>
+ <div
+ class="bb-risk-expr-editor-group w-full overflow-hidden space-y-2 py-0.5"
+ :class="[root ? '' : 'border rounded-[3px] bg-gray-50']"
+ >
+ <div v-if="!root" class="pl-2.5 pr-1 text-gray-500 flex items-center">
+ <div class="flex-1">
+ <template v-if="args.length > 0">
+ <template v-if="operator === '_||_'">
+ {{
+ $t("custom-approval.security-rule.condition.group.or.description")
+ }}
+ </template>
+ <template v-if="operator === '_&&_'">
+ {{
+ $t(
+ "custom-approval.security-rule.condition.group.and.description"
+ )
+ }}
+ </template>
+ </template>
+ <template v-else>
+ <div>
+ {{
+ $t("custom-approval.security-rule.condition.add-condition-here")
+ }}
+ </div>
+ </template>
+ </div>
+ <div v-if="allowAdmin" class="flex items-center justify-end">
+ <NButton
+ size="tiny"
+ quaternary
+ type="default"
+ :style="`flex-shrink: 0; padding-left: 0; padding-right: 0; --n-width: 22px`"
+ @click="addCondition"
+ >
+ <heroicons:plus class="w-4 h-4" />
+ </NButton>
+ <NButton
+ size="tiny"
+ quaternary
+ type="default"
+ :style="`flex-shrink: 0; padding-left: 0; padding-right: 0; --n-width: 22px;`"
+ @click="emit('remove')"
+ >
+ <heroicons:trash class="w-3.5 h-3.5" />
+ </NButton>
+ </div>
+ </div>
+
+ <div v-if="root && args.length === 0" class="px-1.5 text-gray-500">
+ {{ $t("custom-approval.security-rule.condition.add-condition-here") }}
+ </div>
+ <div
+ v-for="(operand, i) in args"
+ :key="i"
+ class="flex items-start gap-x-1 w-full"
+ :class="[root ? '' : 'px-1']"
+ >
+ <div class="w-14 shrink-0">
+ <div v-if="i === 0" class="pl-1.5 pt-1 text-control">Where</div>
+ <NSelect
+ v-else-if="i === 1 && allowAdmin"
+ v-model:value="operator"
+ :options="OPERATORS"
+ :consistent-menu-width="false"
+ size="small"
+ @update:value="$emit('update')"
+ />
+ <div v-else class="pl-2 pt-1 text-control lowercase">
+ {{ operatorLabel(operator) }}
+ </div>
+ </div>
+ <div class="flex-1 space-y-1 overflow-x-hidden">
+ <ConditionGroup
+ v-if="isConditionGroupExpr(operand)"
+ :expr="operand"
+ @remove="removeConditionGroup(operand)"
+ @update="$emit('update')"
+ />
+ <Condition
+ v-if="isConditionExpr(operand)"
+ :expr="operand"
+ @remove="removeCondition(operand)"
+ @update="$emit('update')"
+ />
+ </div>
+ </div>
+ <div v-if="root && allowAdmin">
+ <NButton size="small" quaternary @click="addCondition">
+ <template #icon><heroicons:plus class="w-4 h-4" /></template>
+ <span>{{ $t("custom-approval.security-rule.condition.add") }}</span>
+ </NButton>
+ <NButton size="small" quaternary @click="addConditionGroup">
+ <template #icon><heroicons:plus class="w-4 h-4" /></template>
+ <span>{{
+ $t("custom-approval.security-rule.condition.add-group")
+ }}</span>
+ <NTooltip>
+ <template #trigger>
+ <heroicons:question-mark-circle class="ml-1 w-3 h-3" />
+ </template>
+ <div>tips here</div>
+ </NTooltip>
+ </NButton>
+ </div>
+ </div>
+</template>
+
+<script lang="ts" setup>
+/* eslint-disable vue/no-mutating-props */
+import { computed } from "vue";
+import { NButton, NSelect, NTooltip, type SelectOption } from "naive-ui";
+
+import {
+ type ConditionExpr,
+ type ConditionGroupExpr,
+ type LogicalOperator,
+ StringFactorList,
+ StringOperatorList,
+ LogicalOperatorList,
+ isConditionGroupExpr,
+ isConditionExpr,
+} from "@/plugins/cel";
+import Condition from "./Condition.vue";
+import { useExprEditorContext } from "./context";
+
+const props = defineProps<{
+ expr: ConditionGroupExpr;
+ root?: boolean;
+}>();
+
+const emit = defineEmits<{
+ (event: "remove"): void;
+ (event: "update"): void;
+}>();
+
+const context = useExprEditorContext();
+const { allowAdmin } = context;
+
+const operator = computed({
+ get() {
+ return props.expr.operator;
+ },
+ set(op) {
+ props.expr.operator = op;
+ },
+});
+const args = computed(() => props.expr.args);
+
+const operatorLabel = (op: LogicalOperator) => {
+ if (op === "_&&_") return "and";
+ if (op === "_||_") return "or";
+ throw new Error(`unknown logical operator "${op}"`);
+};
+
+const OPERATORS: SelectOption[] = [
+ { label: operatorLabel("_&&_"), value: "_&&_" },
+ { label: operatorLabel("_||_"), value: "_||_" },
+];
+
+const addCondition = () => {
+ args.value.push({
+ operator: StringOperatorList[0],
+ args: [StringFactorList[0], ""],
+ });
+ emit("update");
+};
+
+const addConditionGroup = () => {
+ args.value.push({
+ operator: LogicalOperatorList[0],
+ args: [],
+ });
+ emit("update");
+};
+
+const removeCondition = (condition: ConditionExpr) => {
+ const index = args.value.indexOf(condition);
+ if (index >= 0) {
+ args.value.splice(index, 1);
+ emit("update");
+ }
+};
+
+const removeConditionGroup = (group: ConditionGroupExpr) => {
+ const index = args.value.indexOf(group);
+ if (index >= 0) {
+ args.value.splice(index, 1);
+ emit("update");
+ }
+};
+</script>
diff --git a/frontend/src/components/CustomApproval/Settings/components/common/ExprEditor/ExprEditor.vue b/frontend/src/components/CustomApproval/Settings/components/common/ExprEditor/ExprEditor.vue
new file mode 100644
index 0000000000..403ff1920c
--- /dev/null
+++ b/frontend/src/components/CustomApproval/Settings/components/common/ExprEditor/ExprEditor.vue
@@ -0,0 +1,58 @@
+<template>
+ <div class="bb-risk-expr-editor text-sm w-full">
+ <ConditionGroup :expr="expr" :root="true" @update="$emit('update')" />
+ </div>
+</template>
+
+<script lang="ts" setup>
+import { Risk_Source } from "@/types/proto/v1/risk_service";
+import { toRef } from "vue";
+import type { ConditionGroupExpr } from "@/plugins/cel";
+import ConditionGroup from "./ConditionGroup.vue";
+import { provideExprEditorContext } from "./context";
+
+const props = withDefaults(
+ defineProps<{
+ expr: ConditionGroupExpr;
+ allowAdmin?: boolean;
+ allowHighLevelFactors?: boolean;
+ riskSource?: Risk_Source;
+ }>(),
+ {
+ allowAdmin: false,
+ allowHighLevelFactors: false,
+ riskSource: undefined,
+ }
+);
+
+defineEmits<{
+ (event: "update"): void;
+}>();
+
+provideExprEditorContext({
+ allowAdmin: toRef(props, "allowAdmin"),
+ allowHighLevelFactors: toRef(props, "allowHighLevelFactors"),
+ riskSource: toRef(props, "riskSource"),
+});
+</script>
+
+<style>
+.bb-risk-expr-editor .n-base-selection {
+ --n-padding-single: 0 22px 0 8px !important;
+ --n-padding-multiple: 3px 24px 0 5px !important;
+}
+.bb-risk-expr-editor .n-base-selection .n-base-suffix {
+ right: 5px !important;
+}
+
+.bb-risk-expr-editor .n-base-selection-tag-wrapper {
+ padding-right: 2px;
+}
+
+.bb-risk-expr-editor .n-button {
+ --n-padding: 0 6px 0 2px !important;
+}
+.bb-risk-expr-editor .n-button .n-button__icon {
+ margin-right: 0px !important;
+}
+</style>
diff --git a/frontend/src/components/CustomApproval/Settings/components/common/ExprEditor/components/FactorSelect.vue b/frontend/src/components/CustomApproval/Settings/components/common/ExprEditor/components/FactorSelect.vue
new file mode 100644
index 0000000000..e9b6a62766
--- /dev/null
+++ b/frontend/src/components/CustomApproval/Settings/components/common/ExprEditor/components/FactorSelect.vue
@@ -0,0 +1,81 @@
+<template>
+ <NSelect
+ v-model:value="factor"
+ :options="options"
+ :consistent-menu-width="false"
+ :disabled="!allowAdmin"
+ size="small"
+ style="width: auto; max-width: 9rem; flex-shrink: 0"
+ />
+</template>
+
+<script lang="ts" setup>
+/* eslint-disable vue/no-mutating-props */
+
+import { computed, watch } from "vue";
+import { SelectOption } from "naive-ui";
+
+import {
+ type ConditionExpr,
+ type Factor,
+ FactorList,
+ isHighLevelFactor,
+} from "@/plugins/cel";
+import { Risk_Source } from "@/types/proto/v1/risk_service";
+import { useExprEditorContext } from "../context";
+
+const props = defineProps<{
+ expr: ConditionExpr;
+}>();
+
+const { allowAdmin, allowHighLevelFactors, riskSource } =
+ useExprEditorContext();
+
+const factor = computed({
+ get() {
+ return props.expr.args[0];
+ },
+ set(factor) {
+ props.expr.args[0] = factor;
+ },
+});
+
+const factorList = computed((): Factor[] => {
+ const factorList: Factor[] = [];
+ const source = riskSource.value;
+ switch (source) {
+ case Risk_Source.DDL:
+ factorList.push(...FactorList.DDL);
+ break;
+ case Risk_Source.DML:
+ factorList.push(...FactorList.DML);
+ break;
+ case Risk_Source.CREATE_DATABASE:
+ factorList.push(...FactorList.CreateDatabase);
+ break;
+ default:
+ // unsupported namespace
+ return [];
+ }
+ if (allowHighLevelFactors.value) return factorList;
+ return factorList.filter((factor) => !isHighLevelFactor(factor));
+});
+
+const options = computed(() => {
+ return factorList.value.map<SelectOption>((v) => ({
+ label: v,
+ value: v,
+ }));
+});
+
+watch(
+ [factor, factorList],
+ () => {
+ if (factorList.value.length === 0) return;
+ if (!factorList.value.includes(factor.value)) {
+ factor.value = factorList.value[0];
+ }
+ },
+ { immediate: true }
+);
+</script>
diff --git a/frontend/src/components/CustomApproval/Settings/components/common/ExprEditor/components/MultiSelect.vue b/frontend/src/components/CustomApproval/Settings/components/common/ExprEditor/components/MultiSelect.vue
new file mode 100644
index 0000000000..a4a326dd15
--- /dev/null
+++ b/frontend/src/components/CustomApproval/Settings/components/common/ExprEditor/components/MultiSelect.vue
@@ -0,0 +1,81 @@
+<template>
+ <NSelect
+ :value="value"
+ :options="options"
+ :multiple="true"
+ :consistent-menu-width="false"
+ :placeholder="$t('custom-approval.security-rule.condition.select-value')"
+ :disabled="!allowAdmin"
+ max-tag-count="responsive"
+ size="small"
+ style="min-width: 12rem; width: auto; overflow-x: hidden"
+ @update:value="$emit('update:value', $event)"
+ >
+ <template #action>
+ <NCheckbox
+ :label="$t('common.all')"
+ v-bind="checkAllState"
+ @update:checked="toggleCheckAll"
+ />
+ </template>
+ </NSelect>
+</template>
+
+<script lang="ts" setup>
+import { computed, toRef, watch } from "vue";
+import { NCheckbox, NSelect } from "naive-ui";
+
+import { type ConditionExpr } from "@/plugins/cel";
+import { useExprEditorContext } from "../context";
+import { useSelectOptions } from "./common";
+
+const props = defineProps<{
+ value: string[] | number[];
+ expr: ConditionExpr;
+}>();
+
+const emit = defineEmits<{
+ (event: "update:value", value: string[] | number[]): void;
+}>();
+
+const context = useExprEditorContext();
+const { allowAdmin } = context;
+
+const options = useSelectOptions(toRef(props, "expr"));
+
+const checkAllState = computed(() => {
+ const selected = new Set<any>(props.value);
+ const checked = options.value.every((opt) => {
+ return selected.has(opt.value);
+ });
+ const indeterminate = props.value.length > 0 && !checked;
+ return {
+ checked,
+ indeterminate,
+ };
+});
+
+const toggleCheckAll = (on: boolean) => {
+ if (on) {
+ emit(
+ "update:value",
+ options.value.map((opt) => opt.value as string)
+ );
+ } else {
+ emit("update:value", []);
+ }
+};
+
+watch(
+ [options, () => props.value],
+ () => {
+ const values = new Set(options.value.map((opt) => opt.value));
+ const filtered = (props.value as any[]).filter((v) => values.has(v));
+ if (filtered.length !== props.value.length) {
+ // Some values are not suitable for the select options.
+ emit("update:value", filtered);
+ }
+ },
+ { immediate: true }
+);
+</script>
diff --git a/frontend/src/components/CustomApproval/Settings/components/common/ExprEditor/components/MultiStringInput.vue b/frontend/src/components/CustomApproval/Settings/components/common/ExprEditor/components/MultiStringInput.vue
new file mode 100644
index 0000000000..5fd42d83a2
--- /dev/null
+++ b/frontend/src/components/CustomApproval/Settings/components/common/ExprEditor/components/MultiStringInput.vue
@@ -0,0 +1,35 @@
+<template>
+ <NSelect
+ :value="value"
+ :filterable="true"
+ :multiple="true"
+ :tag="true"
+ :show-arrow="false"
+ :show="false"
+ :consistent-menu-width="false"
+ :placeholder="
+ $t('custom-approval.security-rule.condition.input-value-press-enter')
+ "
+ :disabled="!allowAdmin"
+ max-tag-count="responsive"
+ size="small"
+ style="min-width: 16rem; width: auto; overflow-x: hidden"
+ @update:value="$emit('update:value', $event)"
+ />
+</template>
+
+<script lang="ts" setup>
+import { NSelect } from "naive-ui";
+import { useExprEditorContext } from "../context";
+
+defineProps<{
+ value: string[];
+}>();
+
+defineEmits<{
+ (event: "update:value", value: string[]): void;
+}>();
+
+const context = useExprEditorContext();
+const { allowAdmin } = context;
+</script>
diff --git a/frontend/src/components/CustomApproval/Settings/components/common/ExprEditor/components/NumberInput.vue b/frontend/src/components/CustomApproval/Settings/components/common/ExprEditor/components/NumberInput.vue
new file mode 100644
index 0000000000..59e8e65534
--- /dev/null
+++ b/frontend/src/components/CustomApproval/Settings/components/common/ExprEditor/components/NumberInput.vue
@@ -0,0 +1,27 @@
+<template>
+ <NInputNumber
+ :value="value"
+ :show-button="false"
+ :placeholder="$t('custom-approval.security-rule.condition.input-value')"
+ :disabled="!allowAdmin"
+ size="small"
+ style="width: auto; max-width: 5rem; overflow-x: hidden"
+ @update:value="$emit('update:value', $event ?? 0)"
+ />
+</template>
+
+<script lang="ts" setup>
+import { NInputNumber } from "naive-ui";
+import { useExprEditorContext } from "../context";
+
+defineProps<{
+ value: number;
+}>();
+
+defineEmits<{
+ (event: "update:value", value: number): void;
+}>();
+
+const context = useExprEditorContext();
+const { allowAdmin } = context;
+</script>
diff --git a/frontend/src/components/CustomApproval/Settings/components/common/ExprEditor/components/OperatorSelect.vue b/frontend/src/components/CustomApproval/Settings/components/common/ExprEditor/components/OperatorSelect.vue
new file mode 100644
index 0000000000..113d3edfc4
--- /dev/null
+++ b/frontend/src/components/CustomApproval/Settings/components/common/ExprEditor/components/OperatorSelect.vue
@@ -0,0 +1,79 @@
+<!-- eslint-disable vue/no-mutating-props -->
+<template>
+ <NSelect
+ v-model:value="operator"
+ :options="options"
+ :consistent-menu-width="false"
+ :disabled="!allowAdmin"
+ size="small"
+ style="width: auto; max-width: 7rem; min-width: 2.5rem; flex-shrink: 0"
+ />
+</template>
+
+<script lang="ts" setup>
+/* eslint-disable vue/no-mutating-props */
+
+import { SelectOption } from "naive-ui";
+import { computed, watch } from "vue";
+import {
+ type Operator,
+ type ConditionOperator,
+ type ConditionExpr,
+ getOperatorListByFactor,
+} from "@/plugins/cel";
+import { useExprEditorContext } from "../context";
+
+const props = defineProps<{
+ expr: ConditionExpr;
+}>();
+
+const context = useExprEditorContext();
+const { allowAdmin } = context;
+
+const operator = computed({
+ get() {
+ return props.expr.operator;
+ },
+ set(op) {
+ props.expr.operator = op;
+ },
+});
+
+const factor = computed(() => {
+ return props.expr.args[0];
+});
+
+const OPERATOR_DICT = new Map([
+ ["_==_", "=="],
+ ["_!=_", "!="],
+ ["_<_", "<"],
+ ["_<=_", "≤"],
+ ["_>=_", "≥"],
+ ["_>_", ">"],
+]);
+
+const options = computed(() => {
+ const operators = getOperatorListByFactor(factor.value);
+
+ const mapOption = (op: Operator): SelectOption => {
+ const label = OPERATOR_DICT.get(op) ?? op;
+ return {
+ label,
+ value: op,
+ };
+ };
+ return operators.map(mapOption);
+});
+
+// normalize operator when factor changed
+watch(
+ [options, () => props.expr.operator],
+ () => {
+ if (options.value.length === 0) return;
+ if (!options.value.find((opt) => opt.value === props.expr.operator)) {
+ props.expr.operator = options.value[0].value as ConditionOperator;
+ }
+ },
+ { immediate: true }
+);
+</script>
diff --git a/frontend/src/components/CustomApproval/Settings/components/common/ExprEditor/components/SingleSelect.vue b/frontend/src/components/CustomApproval/Settings/components/common/ExprEditor/components/SingleSelect.vue
new file mode 100644
index 0000000000..11f06c99b6
--- /dev/null
+++ b/frontend/src/components/CustomApproval/Settings/components/common/ExprEditor/components/SingleSelect.vue
@@ -0,0 +1,46 @@
+<template>
+ <NSelect
+ :value="value"
+ :options="options"
+ :consistent-menu-width="false"
+ :placeholder="$t('custom-approval.security-rule.condition.select-value')"
+ :disabled="!allowAdmin"
+ size="small"
+ style="min-width: 7rem; width: auto; overflow-x: hidden"
+ @update:value="$emit('update:value', $event)"
+ />
+</template>
+
+<script lang="ts" setup>
+import { toRef, watch } from "vue";
+import { NSelect } from "naive-ui";
+
+import { type ConditionExpr } from "@/plugins/cel";
+import { useExprEditorContext } from "../context";
+import { useSelectOptions } from "./common";
+
+const props = defineProps<{
+ value: string | number;
+ expr: ConditionExpr;
+}>();
+
+const emit = defineEmits<{
+ (event: "update:value", value: string | number): void;
+}>();
+
+const context = useExprEditorContext();
+const { allowAdmin } = context;
+
+const options = useSelectOptions(toRef(props, "expr"));
+
+watch(
+ [options, () => props.value],
+ () => {
+ if (options.value.length === 0) return;
+ if (!options.value.find((opt) => opt.value === props.value)) {
+ emit("update:value", options.value[0].value!);
+ }
+ },
+ { immediate: true }
+);
+</script>
diff --git a/frontend/src/components/CustomApproval/Settings/components/common/ExprEditor/components/StringInput.vue b/frontend/src/components/CustomApproval/Settings/components/common/ExprEditor/components/StringInput.vue
new file mode 100644
index 0000000000..eb0be7282c
--- /dev/null
+++ b/frontend/src/components/CustomApproval/Settings/components/common/ExprEditor/components/StringInput.vue
@@ -0,0 +1,26 @@
+<template>
+ <NInput
+ :value="value"
+ :placeholder="$t('custom-approval.security-rule.condition.input-value')"
+ :disabled="!allowAdmin"
+ size="small"
+ style="min-width: 7rem; width: auto; overflow-x: hidden"
+ @update:value="$emit('update:value', $event)"
+ />
+</template>
+
+<script lang="ts" setup>
+import { NInput } from "naive-ui";
+import { useExprEditorContext } from "../context";
+
+defineProps<{
+ value: string;
+}>();
+
+defineEmits<{
+ (event: "update:value", value: string): void;
+}>();
+
+const context = useExprEditorContext();
+const { allowAdmin } = context;
+</script>
diff --git a/frontend/src/components/CustomApproval/Settings/components/common/ExprEditor/components/ValueInput.vue b/frontend/src/components/CustomApproval/Settings/components/common/ExprEditor/components/ValueInput.vue
new file mode 100644
index 0000000000..f6273dfbeb
--- /dev/null
+++ b/frontend/src/components/CustomApproval/Settings/components/common/ExprEditor/components/ValueInput.vue
@@ -0,0 +1,161 @@
+<template>
+ <template v-if="inputType === 'INPUT'">
+ <NumberInput
+ v-if="isNumberValue"
+ :value="getNumberValue()"
+ @update:value="setNumberValue($event)"
+ />
+ <StringInput
+ v-if="isStringValue"
+ :value="getStringValue()"
+ @update:value="setStringValue($event)"
+ />
+ </template>
+ <template v-if="inputType === 'SINGLE-SELECT'">
+ <SingleSelect
+ v-if="isNumberValue"
+ :value="getNumberValue()"
+ :expr="expr"
+ @update:value="setNumberValue($event as number)"
+ />
+ <SingleSelect
+ v-if="isStringValue"
+ :value="getStringValue()"
+ :expr="expr"
+ @update:value="setStringValue($event as string)"
+ />
+ </template>
+ <template v-if="inputType === 'MULTI-SELECT'">
+ <MultiSelect
+ :value="getArrayValue()"
+ :expr="expr"
+ @update:value="setArrayValue($event)"
+ />
+ </template>
+ <template v-if="inputType === 'MULTI-INPUT'">
+ <MultiStringInput
+ :value="getStringArrayValue()"
+ :expr="expr"
+ @update:value="setArrayValue($event)"
+ />
+ </template>
+</template>
+
+<script lang="ts" setup>
+/* eslint-disable vue/no-mutating-props */
+
+import { computed, watch } from "vue";
+import { isNumber } from "lodash-es";
+
+import {
+ type ConditionExpr,
+ isEqualityOperator,
+ isCollectionOperator,
+ isStringOperator,
+ isCompareOperator,
+ isNumberFactor,
+ isStringFactor,
+} from "@/plugins/cel";
+import NumberInput from "./NumberInput.vue";
+import StringInput from "./StringInput.vue";
+import SingleSelect from "./SingleSelect.vue";
+import MultiSelect from "./MultiSelect.vue";
+import MultiStringInput from "./MultiStringInput.vue";
+import { factorSupportDropdown } from "./common";
+
+type InputType = "INPUT" | "SINGLE-SELECT" | "MULTI-SELECT" | "MULTI-INPUT";
+
+const props = defineProps<{
+ expr: ConditionExpr;
+}>();
+
+const operator = computed(() => {
+ return props.expr.operator;
+});
+
+const factor = computed(() => {
+ return props.expr.args[0];
+});
+
+const isNumberValue = computed(() => {
+ if (isCompareOperator(operator.value)) return true;
+ if (isEqualityOperator(operator.value) && isNumberFactor(factor.value)) {
+ return true;
+ }
+ return false;
+});
+const isStringValue = computed(() => {
+ if (isStringOperator(operator.value)) return true;
+ if (isEqualityOperator(operator.value) && isStringFactor(factor.value)) {
+ return true;
+ }
+ return false;
+});
+const isArrayValue = computed(() => {
+ return isCollectionOperator(operator.value);
+});
+const inputType = computed((): InputType => {
+ if (isArrayValue.value) {
+ return factorSupportDropdown(factor.value) ? "MULTI-SELECT" : "MULTI-INPUT";
+ }
+ if (isEqualityOperator(operator.value)) {
+ if (factorSupportDropdown(factor.value)) {
+ return "SINGLE-SELECT";
+ }
+ }
+ return "INPUT";
+});
+
+const getNumberValue = () => {
+ const value = props.expr.args[1];
+ if (!isNumber(value)) return 0;
+ return value;
+};
+const setNumberValue = (value: number) => {
+ props.expr.args[1] = value;
+};
+
+const getStringValue = () => {
+ const value = props.expr.args[1];
+ if (typeof value !== "string") return "";
+ return value;
+};
+const setStringValue = (value: string) => {
+ props.expr.args[1] = value;
+};
+
+const getArrayValue = () => {
+ const values = props.expr.args[1];
+ if (!Array.isArray(values)) return [];
+ return values;
+};
+const getStringArrayValue = () => getArrayValue() as string[];
+const setArrayValue = (values: string[] | number[]) => {
+ props.expr.args[1] = values;
+};
+
+// clean up value type when factor and operator changed
+watch(
+ [factor, operator, () => props.expr.args[1]],
+ ([factor, operator, value]) => {
+ if (isEqualityOperator(operator)) {
+ if (isNumberFactor(factor) && !isNumber(value)) {
+ setNumberValue(0);
+ }
+ if (isStringFactor(factor) && typeof value !== "string") {
+ setStringValue("");
+ }
+ }
+ if (isCompareOperator(operator) && !isNumber(value)) {
+ setNumberValue(0);
+ }
+ if (isCollectionOperator(operator) && !Array.isArray(value)) {
+ setArrayValue([]);
+ }
+ if (isStringOperator(operator) && typeof value !== "string") {
+ setStringValue("");
+ }
+ },
+ { immediate: true }
+);
+</script>
diff --git a/frontend/src/components/CustomApproval/Settings/components/common/ExprEditor/components/common.ts b/frontend/src/components/CustomApproval/Settings/components/common/ExprEditor/components/common.ts
new file mode 100644
index 0000000000..61e3a579b4
--- /dev/null
+++ b/frontend/src/components/CustomApproval/Settings/components/common/ExprEditor/components/common.ts
@@ -0,0 +1,111 @@
+import { type Ref, computed } from "vue";
+import type { SelectOption } from "naive-ui";
+
+import { ConditionExpr, Factor, SQLTypeList } from "@/plugins/cel";
+import { useExprEditorContext } from "../context";
+import { useCurrentUser, useEnvironmentStore, useProjectStore } from "@/store";
+import {
+ engineName,
+ EngineTypeList,
+ PresetRiskLevelList,
+ SupportedSourceList,
+} from "@/types";
+import { Risk_Source, risk_SourceToJSON } from "@/types/proto/v1/risk_service";
+import { levelText } from "../../../RiskCenter/common";
+
+export const useSelectOptions = (expr: Ref<ConditionExpr>) => {
+ const context = useExprEditorContext();
+ const { riskSource } = context;
+
+ const getEnvironmentOptions = () => {
+ const environmentList = useEnvironmentStore().getEnvironmentList();
+ return environmentList.map<SelectOption>((env) => ({
+ label: env.name,
+ value: env.resourceId,
+ }));
+ };
+
+ const getProjectOptions = () => {
+ const user = useCurrentUser().value;
+ const projectList = useProjectStore().getProjectListByUser(user.id);
+ return projectList.map<SelectOption>((proj) => ({
+ label: proj.name,
+ value: proj.resourceId,
+ }));
+ };
+
+ const getDBEndingOptions = () => {
+ return EngineTypeList.map<SelectOption>((type) => ({
+ label: engineName(type),
+ value: type,
+ }));
+ };
+
+ const getRiskOptions = () => {
+ return PresetRiskLevelList.map<SelectOption>(({ level }) => ({
+ label: levelText(level),
+ value: level,
+ }));
+ };
+
+ const getSourceOptions = () => {
+ return SupportedSourceList.map<SelectOption>((source) => ({
+ label: risk_SourceToJSON(source),
+ value: source,
+ }));
+ };
+
+ const getSQLTypeOptions = () => {
+ const source = riskSource.value;
+ const mapOptions = (values: readonly string[]) => {
+ return values.map<SelectOption>((v) => ({
+ label: v,
+ value: v,
+ }));
+ };
+ switch (source) {
+ case Risk_Source.DDL:
+ return mapOptions(SQLTypeList.DDL);
+ case Risk_Source.DML:
+ return mapOptions(SQLTypeList.DML);
+ }
+ // unsupported source
+ return [];
+ };
+
+ const options = computed(() => {
+ const factor = expr.value.args[0];
+ if (factor === "environment_id") {
+ return getEnvironmentOptions();
+ }
+ if (factor === "project_id") {
+ return getProjectOptions();
+ }
+ if (factor === "db_engine") {
+ return getDBEndingOptions();
+ }
+ if (factor === "risk") {
+ return getRiskOptions();
+ }
+ if (factor === "source") {
+ return getSourceOptions();
+ }
+ if (factor === "sql_type") {
+ return getSQLTypeOptions();
+ }
+ return [];
+ });
+
+ return options;
+};
+
+export const factorSupportDropdown = (factor: Factor): boolean => {
+ const list: Factor[] = [
+ "environment_id",
+ "db_engine",
+ "sql_type",
+ "risk",
+ "source",
+ ];
+ return list.includes(factor);
+};
diff --git a/frontend/src/components/CustomApproval/Settings/components/common/ExprEditor/components/index.ts b/frontend/src/components/CustomApproval/Settings/components/common/ExprEditor/components/index.ts
new file mode 100644
index 0000000000..faeac7beeb
--- /dev/null
+++ b/frontend/src/components/CustomApproval/Settings/components/common/ExprEditor/components/index.ts
@@ -0,0 +1,5 @@
+import FactorSelect from "./FactorSelect.vue";
+import OperatorSelect from "./OperatorSelect.vue";
+import ValueInput from "./ValueInput.vue";
+
+export { FactorSelect, OperatorSelect, ValueInput };
diff --git a/frontend/src/components/CustomApproval/Settings/components/common/ExprEditor/context.ts b/frontend/src/components/CustomApproval/Settings/components/common/ExprEditor/context.ts
new file mode 100644
index 0000000000..b597cc4536
--- /dev/null
+++ b/frontend/src/components/CustomApproval/Settings/components/common/ExprEditor/context.ts
@@ -0,0 +1,20 @@
+import { Risk_Source } from "@/types/proto/v1/risk_service";
+import { inject, provide, type InjectionKey, type Ref } from "vue";
+
+export type ExprEditorContext = {
+ allowAdmin: Ref<boolean>;
+ allowHighLevelFactors: Ref<boolean>;
+ riskSource: Ref<Risk_Source | undefined>;
+};
+
+export const KEY = Symbol(
+ "bb.custom-approval.expr-editor"
+) as InjectionKey<ExprEditorContext>;
+
+export const useExprEditorContext = () => {
+ return inject(KEY)!;
+};
+
+export const provideExprEditorContext = (context: ExprEditorContext) => {
+ provide(KEY, context);
+};
diff --git a/frontend/src/components/CustomApproval/Settings/components/common/ExprEditor/index.ts b/frontend/src/components/CustomApproval/Settings/components/common/ExprEditor/index.ts
new file mode 100644
index 0000000000..497ff06640
--- /dev/null
+++ b/frontend/src/components/CustomApproval/Settings/components/common/ExprEditor/index.ts
@@ -0,0 +1,3 @@
+import ExprEditor from "./ExprEditor.vue";
+
+export default ExprEditor;
diff --git a/frontend/src/components/CustomApproval/Settings/components/common/SpinnerButton.vue b/frontend/src/components/CustomApproval/Settings/components/common/SpinnerButton.vue
new file mode 100644
index 0000000000..15012b6524
--- /dev/null
+++ b/frontend/src/components/CustomApproval/Settings/components/common/SpinnerButton.vue
@@ -0,0 +1,64 @@
+<template>
+ <NPopconfirm
+ v-bind="popconfirmProps"
+ :disabled="!tooltip"
+ @positive-click="handleConfirm"
+ >
+ <template #trigger>
+ <NButton
+ :loading="loading"
+ style="--n-icon-margin: 4px; --n-icon-size: 14px"
+ v-bind="buttonAttrs"
+ >
+ <slot />
+ </NButton>
+ </template>
+
+ <div v-if="tooltip" :class="tooltipClass">{{ tooltip }}</div>
+ </NPopconfirm>
+</template>
+
+<script lang="ts">
+import { defineComponent } from "vue";
+defineComponent({
+ inheritAttrs: false,
+});
+</script>
+
+<script lang="ts" setup>
+import { computed, ref, useAttrs } from "vue";
+import { omit } from "lodash-es";
+import { VueClass } from "@/utils";
+import {
+ type ButtonProps,
+ type PopconfirmProps,
+ NButton,
+ NPopconfirm,
+} from "naive-ui";
+
+export interface SpinnerButtonProps extends ButtonProps {
+ onConfirm: () => Promise<any>;
+ tooltip?: string;
+ tooltipClass?: VueClass;
+ popconfirmProps?: PopconfirmProps;
+}
+const props = defineProps<SpinnerButtonProps>();
+
+const attrs = useAttrs();
+const buttonAttrs = computed(() =>
+ omit(attrs, "tooltip", "tooltipClass", "popconfirmProps")
+);
+
+const loading = ref(false);
+
+const handleConfirm = async () => {
+ if (loading.value) return;
+
+ loading.value = true;
+ try {
+ await props.onConfirm();
+ } finally {
+ loading.value = false;
+ }
+};
+</script>
diff --git a/frontend/src/components/CustomApproval/Settings/components/common/SpinnerSwitch.vue b/frontend/src/components/CustomApproval/Settings/components/common/SpinnerSwitch.vue
new file mode 100644
index 0000000000..7e8f797c87
--- /dev/null
+++ b/frontend/src/components/CustomApproval/Settings/components/common/SpinnerSwitch.vue
@@ -0,0 +1,33 @@
+<template>
+ <NSwitch :loading="loading" @update:value="handleToggle" />
+</template>
+
+<script lang="ts">
+import { defineComponent } from "vue";
+defineComponent({
+ inheritAttrs: false,
+});
+</script>
+
+<script lang="ts" setup>
+import { ref } from "vue";
+import { type SwitchProps, NSwitch } from "naive-ui";
+
+export interface SpinnerSwitchProps extends SwitchProps {
+ onToggle: (on: boolean) => Promise<any>;
+}
+const props = defineProps<SpinnerSwitchProps>();
+
+const loading = ref(false);
+
+const handleToggle = async (on: boolean) => {
+ if (loading.value) return;
+
+ loading.value = true;
+ try {
+ await props.onToggle(on);
+ } finally {
+ loading.value = false;
+ }
+};
+</script>
diff --git a/frontend/src/components/CustomApproval/Settings/components/common/index.ts b/frontend/src/components/CustomApproval/Settings/components/common/index.ts
new file mode 100644
index 0000000000..ba43ea87db
--- /dev/null
+++ b/frontend/src/components/CustomApproval/Settings/components/common/index.ts
@@ -0,0 +1,5 @@
+import SpinnerButton from "./SpinnerButton.vue";
+import SpinnerSwitch from "./SpinnerSwitch.vue";
+import ExprEditor from "./ExprEditor";
+
+export { ExprEditor, SpinnerButton, SpinnerSwitch };
diff --git a/frontend/src/components/CustomApproval/Settings/components/index.ts b/frontend/src/components/CustomApproval/Settings/components/index.ts
new file mode 100644
index 0000000000..5a836433b9
--- /dev/null
+++ b/frontend/src/components/CustomApproval/Settings/components/index.ts
@@ -0,0 +1,6 @@
+// import Toolbar from "./Toolbar.vue";
+
+// export * from "./Workflow";
+export * from "./RiskCenter";
+
+// export { Toolbar };
diff --git a/frontend/src/components/CustomApproval/Settings/index.ts b/frontend/src/components/CustomApproval/Settings/index.ts
new file mode 100644
index 0000000000..40b494c5f8
--- /dev/null
+++ b/frontend/src/components/CustomApproval/Settings/index.ts
@@ -0,0 +1 @@
+export * from "./components";
diff --git a/frontend/src/components/CustomApproval/common/index.ts b/frontend/src/components/CustomApproval/common/index.ts
new file mode 100644
index 0000000000..bf61c76c34
--- /dev/null
+++ b/frontend/src/components/CustomApproval/common/index.ts
@@ -0,0 +1 @@
+export * from "./expression";
diff --git a/frontend/src/components/Environment/EnvironmentName.vue b/frontend/src/components/Environment/EnvironmentName.vue
new file mode 100644
index 0000000000..ceb8782819
--- /dev/null
+++ b/frontend/src/components/Environment/EnvironmentName.vue
@@ -0,0 +1,25 @@
+<template>
+ <component :is="tag">
+ {{ environmentName(environment) }}
+ <ProductionEnvironmentIcon
+ :environment="environment"
+ class="!text-current"
+ />
+ </component>
+</template>
+
+<script lang="ts" setup>
+import type { Environment } from "@/types";
+import { environmentName } from "@/utils";
+import ProductionEnvironmentIcon from "./ProductionEnvironmentIcon.vue";
+
+withDefaults(
+ defineProps<{
+ environment: Environment;
+ tag?: string;
+ }>(),
+ {
+ tag: "span",
+ }
+);
+</script>
diff --git a/frontend/src/grpcweb/index.ts b/frontend/src/grpcweb/index.ts
index 6450014d53..4bba5dfd22 100644
--- a/frontend/src/grpcweb/index.ts
+++ b/frontend/src/grpcweb/index.ts
@@ -9,6 +9,8 @@ import { EnvironmentServiceDefinition } from "@/types/proto/v1/environment_servi
import { InstanceServiceDefinition } from "@/types/proto/v1/instance_service";
import { ProjectServiceDefinition } from "@/types/proto/v1/project_service";
import { SQLServiceDefinition } from "@/types/proto/v1/sql_service";
+import { RiskServiceDefinition } from "@/types/proto/v1/risk_service";
+// import { ApprovalTemplateServiceDefinition } from "@/types/proto/v1/approval_template_service";
// Create each grpc service client.
// Reference: https://github.com/deeplay-io/nice-grpc/blob/master/packages/nice-grpc-web/README.md
@@ -51,6 +53,16 @@ export const identityProviderClient = clientFactory.create(
channel
);
+export const riskServiceClient = clientFactory.create(
+ RiskServiceDefinition,
+ channel
+);
+
+// export const approvalTemplateServiceClient = clientFactory.create(
+// ApprovalTemplateServiceDefinition,
+// channel
+// );
+
export const sqlClient = clientFactory.create(SQLServiceDefinition, channel);
// e.g. How to use `authServiceClient`?
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index 567593b1c4..490fa06bd4 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -228,7 +228,10 @@
"off": "Off",
"verify": "Verify",
"regenerate": "Regenerate",
- "download": "Download"
+ "download": "Download",
+ "will-lose-unsaved-data": "Will lose any unsaved data.",
+ "deleted": "Deleted",
+ "will-override-current-data": "Will override current data."
},
"error-page": {
"go-back-home": "Go back home"
@@ -1734,6 +1737,10 @@
"title": "Unlock 100+ SQL Review checks",
"desc": "Specify SQL lint rules to adopt SQL best practice and enforce schema consistency across the engineering organization."
},
+ "bb-feature-custom-approval": {
+ "title": "Custom approval",
+ "desc": "Configure security risk level and approval flow for different tasks."
+ },
"bb-feature-vcs-schema-write-back": {
"title": "Schema write-back",
"desc": "After a successful schema change, schema write-back enables Bytebase to write back the latest full schema snapshot to your VCS repository."
@@ -2064,5 +2071,107 @@
"statement-copied": "Statement copied to clipboard",
"dont-show-again": "Don't show again"
}
+ },
+ "custom-approval": {
+ "self": "Custom Approval",
+ "security-rule": {
+ "self": "Security rule",
+ "security-rules": "Security rules",
+ "description": "For each operation type, configure custom condition, risk and approval flow. ",
+ "x-risk-rules": {
+ "low": "Low Risk Rules",
+ "moderate": "Moderate Risk Rules",
+ "high": "High Risk Rules"
+ },
+ "active": "Active",
+ "add-rule": "Add rule",
+ "edit-rule": "Edit rule",
+ "delete": "Delete security rule",
+ "default-rules": {
+ "self": "Default rules",
+ "description": "The default rules will be executed when an issue fails to comply with the custom rules."
+ },
+ "risk": {
+ "self": "Risk",
+ "select": "Select risk",
+ "risk-level": {
+ "100": "Low",
+ "200": "Moderate",
+ "300": "High"
+ },
+ "namespace": {
+ "dml": "DML",
+ "ddl": "DDL",
+ "create_database": "Create Database"
+ }
+ },
+ "condition": {
+ "self": "Condition",
+ "description-tips": "A condition is a rule that can be configured via an expression. For example, the condition \"Environment is prod\" will filter outer issues executed in the \"prod\" environment.",
+ "add": "Add condition",
+ "add-group": "Add condition group",
+ "group": {
+ "or": {
+ "description": "Any of the following are true..."
+ },
+ "and": {
+ "description": "All of the following are true..."
+ }
+ },
+ "input-value": "Input value",
+ "add-condition-here": "Add condition here",
+ "select-value": "Select value",
+ "input-value-press-enter": "Input value, press Enter to confirm"
+ },
+ "template": {
+ "templates": "Templates",
+ "load": "Load",
+ "presets": {
+ "environment-prod-high": "The risk for the production environment is considered to be high.",
+ "environment-dev-low": "The risk value for the development environment is considered to be low.",
+ "dml-in-environment-prod-10k-rows-high": "In the production environment, if the number of rows to be updated or deleted exceeds 10000, the risk is considered to be high.",
+ "create-database-in-environment-prod-moderate": "Creating a database in the production environment is considered to be a moderate risk."
+ },
+ "load-template": "Load template",
+ "view": "View template"
+ },
+ "rule-name": "Rule name",
+ "view-rule": "View rule",
+ "source": {
+ "select": "Select type",
+ "self": "Type"
+ },
+ "input-rule-name": "Input rule name",
+ "search": "Search rule"
+ },
+ "approval-flow": {
+ "self": "Approval flow",
+ "approval-flows": "Approval flows",
+ "approval-nodes": "Approval nodes",
+ "type": {
+ "system": "System",
+ "custom": "Custom"
+ },
+ "delete": "Delete approval flow",
+ "search": "Search approval flow",
+ "select": "Select approval flow",
+ "create-approval-flow": "Create approval flow",
+ "edit-approval-flow": "Edit approval flow",
+ "node": {
+ "nodes": "Approval nodes",
+ "description": "Only one approval is required on this node when there are multiple approvers.",
+ "order": "Order",
+ "approver": "Approver",
+ "add": "Add node",
+ "delete": "Delete approval node"
+ },
+ "view-approval-flow": "View approval flow"
+ },
+ "risk": {
+ "risk-center": "Risk Center"
+ },
+ "workflow-center": {
+ "workflow": "Workflow"
+ }
}
}
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index 332066a5cc..e2a1723671 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -226,7 +226,10 @@
"off": "关",
"verify": "验证",
"regenerate": "重新生成",
- "download": "下载"
+ "download": "下载",
+ "will-lose-unsaved-data": "这会丢失当前所有未保存的数据。",
+ "deleted": "已删除",
+ "will-override-current-data": "将会覆盖当前数据。"
},
"error-page": {
"go-back-home": "回到主页"
@@ -1733,6 +1736,10 @@
"title": "解锁 100+ SQL 审核策略",
"desc": "配置各种 SQL lint 规则,以在研发组织中落地 SQL 最佳实践,保障 Schema 的规范一致性。"
},
+ "bb-feature-custom-approval": {
+ "title": "自定义审批",
+ "desc": "为不同的任务配置安全风险等级和自定义审批流。"
+ },
"bb-feature-vcs-schema-write-back": {
"title": "Schema 回写",
"desc": "当一个 Schema 变更完成后,可以将最新的 Schema 快照回写到 VCS。"
@@ -2061,5 +2068,107 @@
"statement-copied": "语句已复制到剪贴板",
"dont-show-again": "不再显示"
}
+ },
+ "custom-approval": {
+ "self": "自定义审批",
+ "security-rule": {
+ "self": "安全规则",
+ "security-rules": "安全规则",
+ "description": "对每种操作类型,配置自定义条件、风险和审批流。",
+ "x-risk-rules": {
+ "low": "低风险规则",
+ "moderate": "中风险规则",
+ "high": "高风险规则"
+ },
+ "active": "开启",
+ "add-rule": "添加规则",
+ "edit-rule": "编辑规则",
+ "delete": "删除安全规则",
+ "default-rules": {
+ "self": "默认规则",
+ "description": "当工单不符合自定义规则时,将会执行默认规则。"
+ },
+ "risk": {
+ "self": "风险",
+ "select": "选择风险",
+ "risk-level": {
+ "100": "低",
+ "200": "中",
+ "300": "高"
+ },
+ "namespace": {
+ "dml": "DML",
+ "ddl": "DDL",
+ "create_database": "创建数据库"
+ }
+ },
+ "condition": {
+ "self": "条件",
+ "description-tips": "条件是通过表达式配置的规则。例如:条件「环境 为 prod」将会过滤出在「prod」环境中执行的工单。",
+ "add": "添加条件",
+ "add-group": "添加条件组",
+ "group": {
+ "or": {
+ "description": "以下任一为真…"
+ },
+ "and": {
+ "description": "以下全部为真…"
+ }
+ },
+ "input-value": "输入值",
+ "add-condition-here": "在这里添加条件",
+ "select-value": "选择值",
+ "input-value-press-enter": "输入值,按回车确认"
+ },
+ "template": {
+ "templates": "模板",
+ "load": "加载",
+ "presets": {
+ "environment-prod-high": "生产环境,默认为高风险",
+ "environment-dev-low": "开发环境,默认为低风险",
+ "dml-in-environment-prod-10k-rows-high": "生产环境中更新或删除的数据行数超过 10000,默认为高风险",
+ "create-database-in-environment-prod-moderate": "在生产环境中创建数据库,默认为中风险"
+ },
+ "load-template": "加载模板",
+ "view": "查看模板"
+ },
+ "rule-name": "规则名称",
+ "view-rule": "查看规则",
+ "source": {
+ "select": "选择类型",
+ "self": "类型"
+ },
+ "input-rule-name": "输入规则名称",
+ "search": "搜索规则"
+ },
+ "approval-flow": {
+ "self": "审批流",
+ "approval-flows": "审批流",
+ "approval-nodes": "审批节点",
+ "type": {
+ "system": "系统",
+ "custom": "自定义"
+ },
+ "delete": "删除审批流",
+ "search": "搜索审批流",
+ "select": "选择审批流",
+ "create-approval-flow": "创建审批流",
+ "edit-approval-flow": "编辑审批流",
+ "node": {
+ "nodes": "审批节点",
+ "description": "当一个节点上有多个审批人时,只需要一次审批通过。",
+ "approver": "审批人",
+ "add": "增加节点",
+ "delete": "删除审批节点",
+ "order": "顺序"
+ },
+ "view-approval-flow": "查看审批流"
+ },
+ "risk": {
+ "risk-center": "风险中心"
+ },
+ "workflow-center": {
+ "workflow": "工作流"
+ }
}
}
diff --git a/frontend/src/plugins/cel/index.ts b/frontend/src/plugins/cel/index.ts
new file mode 100644
index 0000000000..9c0efa5721
--- /dev/null
+++ b/frontend/src/plugins/cel/index.ts
@@ -0,0 +1,2 @@
+export * from "./types";
+export * from "./logic";
diff --git a/frontend/src/plugins/cel/logic/build.ts b/frontend/src/plugins/cel/logic/build.ts
new file mode 100644
index 0000000000..7643b8899e
--- /dev/null
+++ b/frontend/src/plugins/cel/logic/build.ts
@@ -0,0 +1,124 @@
+import { Expr as CELExpr } from "@/types/proto/google/api/expr/v1alpha1/syntax";
+import type { ConditionExpr, ConditionGroupExpr, SimpleExpr } from "../types";
+import {
+ isEqualityExpr,
+ isCollectionExpr,
+ isConditionExpr,
+ isConditionGroupExpr,
+ isCompareExpr,
+ isStringExpr,
+} from "../types";
+
+// Build CEL expr according to simple expr
+export const buildCELExpr = (expr: SimpleExpr): CELExpr | undefined => {
+ const convert = (expr: ConditionGroupExpr | ConditionExpr): CELExpr => {
+ if (isConditionGroupExpr(expr)) return convertGroup(expr);
+ if (isConditionExpr(expr)) return convertCondition(expr);
+ throw new Error(`unexpected type "${String(expr)}"`);
+ };
+ const convertCondition = (condition: ConditionExpr): CELExpr => {
+ if (isEqualityExpr(condition)) {
+ const { operator, args } = condition;
+ const [factor, value] = args;
+ return wrapCallExpr(operator, [
+ wrapIdentExpr(factor),
+ wrapConstExpr(value),
+ ]);
+ }
+ if (isCompareExpr(condition)) {
+ const { operator, args } = condition;
+ const [factor, value] = args;
+ return wrapCallExpr(operator, [
+ wrapIdentExpr(factor),
+ wrapConstExpr(value),
+ ]);
+ }
+ if (isStringExpr(condition)) {
+ const { operator, args } = condition;
+ const [factor, value] = args;
+ return wrapCallExpr(
+ operator,
+ [wrapConstExpr(value)],
+ wrapIdentExpr(factor)
+ );
+ }
+ if (isCollectionExpr(condition)) {
+ const { operator, args } = condition;
+ const [factor, values] = args;
+ return wrapCallExpr(operator, [
+ wrapIdentExpr(factor),
+ wrapListExpr(values),
+ ]);
+ }
+ throw new Error(`unsupported condition '${JSON.stringify(condition)}'`);
+ };
+ const convertGroup = (group: ConditionGroupExpr): CELExpr => {
+ const { operator, args } = group;
+ if (args.length === 1) {
+ // A dangled Logical Group should be extracted as single condition
+ return convert(args[0]);
+ }
+ return wrapCallExpr(operator, args.map(convert));
+ };
+
+ try {
+ return convert(expr);
+ } catch (err) {
+ console.debug(err);
+ return undefined;
+ }
+};
+
+const wrapCELExpr = (object: any): CELExpr => {
+ return CELExpr.fromJSON(object);
+};
+
+const wrapConstExpr = (value: number | string): CELExpr => {
+ if (typeof value === "string") {
+ return wrapCELExpr({
+ constExpr: {
+ stringValue: value,
+ },
+ });
+ }
+ if (typeof value === "number") {
+ return wrapCELExpr({
+ constExpr: {
+ int64Value: value,
+ },
+ });
+ }
+ throw new Error(`unexpected value "${value}"`);
+};
+const wrapListExpr = (values: string[] | number[]): CELExpr => {
+ return wrapCELExpr({
+ listExpr: {
+ elements: values.map(wrapConstExpr),
+ },
+ });
+};
+
+const wrapIdentExpr = (name: string): CELExpr => {
+ return wrapCELExpr({
+ identExpr: {
+ name,
+ },
+ });
+};
+
+const wrapCallExpr = (
+ operator: string,
+ args: CELExpr[],
+ target?: CELExpr
+): CELExpr => {
+ const object: Record<string, any> = {
+ function: operator,
+ args,
+ };
+ if (target) {
+ object.target = target;
+ }
+ return wrapCELExpr({
+ callExpr: object,
+ });
+};
diff --git a/frontend/src/plugins/cel/logic/index.ts b/frontend/src/plugins/cel/logic/index.ts
new file mode 100644
index 0000000000..a80f116f9a
--- /dev/null
+++ b/frontend/src/plugins/cel/logic/index.ts
@@ -0,0 +1,3 @@
+export * from "./resolve";
+export * from "./build";
+export * from "./validate";
diff --git a/frontend/src/plugins/cel/logic/resolve.ts b/frontend/src/plugins/cel/logic/resolve.ts
new file mode 100644
index 0000000000..733b338acb
--- /dev/null
+++ b/frontend/src/plugins/cel/logic/resolve.ts
@@ -0,0 +1,153 @@
+import { Expr as CELExpr } from "@/types/proto/google/api/expr/v1alpha1/syntax";
+import type {
+ NumberFactor,
+ StringFactor,
+ Operator,
+ CollectionOperator,
+ CompareOperator,
+ StringOperator,
+ EqualityOperator,
+ SimpleExpr,
+ CollectionExpr,
+ ConditionExpr,
+ ConditionGroupExpr,
+ CompareExpr,
+ EqualityExpr,
+ StringExpr,
+} from "../types";
+import {
+ LogicalOperatorList,
+ isEqualityOperator,
+ isConditionGroupExpr,
+ isCollectionOperator,
+ isLogicalOperator,
+ isCompareOperator,
+ isStringOperator,
+ isNumberFactor,
+ isStringFactor,
+} from "../types";
+
+// For simplify UI implementation, the "root" condition need to be a group.
+export const wrapAsGroup = (expr: SimpleExpr): ConditionGroupExpr => {
+ if (isConditionGroupExpr(expr)) return expr;
+ return {
+ operator: "_&&_",
+ args: [expr],
+ };
+};
+
+// Convert common expr to simple expr
+export const resolveCELExpr = (expr: CELExpr): SimpleExpr => {
+ const dfs = (expr: CELExpr): ConditionGroupExpr | ConditionExpr => {
+ const { callExpr } = expr;
+ if (!callExpr) {
+ return emptySimpleExpr();
+ // throw new Error(`unsupported expr "${JSON.stringify(expr)}"`);
+ }
+
+ const { args } = callExpr;
+ const operator = callExpr.function as Operator;
+ if (isLogicalOperator(operator)) {
+ const group: ConditionGroupExpr = {
+ operator,
+ args: args.map(dfs),
+ };
+ return group;
+ }
+ if (isEqualityOperator(operator)) {
+ return resolveEqualityExpr(expr);
+ }
+ if (isCompareOperator(operator)) {
+ return resolveCompareExpr(expr);
+ }
+ if (isStringOperator(operator)) {
+ return resolveStringExpr(expr);
+ }
+ if (isCollectionOperator(operator)) {
+ return resolveCollectionExpr(expr);
+ }
+ throw new Error(`unsupported expr "${JSON.stringify(expr)}"`);
+ };
+ return dfs(expr);
+};
+
+const resolveEqualityExpr = (expr: CELExpr): EqualityExpr => {
+ const operator = expr.callExpr!.function as EqualityOperator;
+ const [factorExpr, valueExpr] = expr.callExpr!.args;
+ const factor = factorExpr.identExpr!.name;
+ if (isNumberFactor(factor)) {
+ return {
+ operator,
+ args: [factor, valueExpr.constExpr!.int64Value! ?? 0],
+ };
+ }
+ if (isStringFactor(factor)) {
+ return {
+ operator,
+ args: [factor, valueExpr.constExpr!.stringValue! ?? ""],
+ };
+ }
+ throw new Error(`cannot resolve expr ${JSON.stringify(expr)}`);
+};
+
+const resolveCompareExpr = (expr: CELExpr): CompareExpr => {
+ const operator = expr.callExpr!.function as CompareOperator;
+ const [factor, value] = expr.callExpr!.args;
+ return {
+ operator,
+ args: [
+ factor.identExpr!.name as NumberFactor,
+ value.constExpr!.int64Value!,
+ ],
+ };
+};
+
+const resolveStringExpr = (expr: CELExpr): StringExpr => {
+ const operator = expr.callExpr!.function as StringOperator;
+ const factor = expr.callExpr!.target!;
+ const value = expr.callExpr!.args[0];
+ return {
+ operator,
+ args: [
+ factor.identExpr!.name as StringFactor,
+ value.constExpr!.stringValue!,
+ ],
+ };
+};
+
+const resolveCollectionExpr = (expr: CELExpr): CollectionExpr => {
+ const operator = expr.callExpr!.function as CollectionOperator;
+ const [factorExpr, valuesExpr] = expr.callExpr!.args;
+ const factor = factorExpr.identExpr!.name;
+ if (isNumberFactor(factor)) {
+ return {
+ operator,
+ args: [
+ factor,
+ valuesExpr.listExpr?.elements?.map(
+ (constant) => constant.constExpr?.int64Value ?? 0
+ ) ?? [],
+ ],
+ };
+ }
+ if (isStringFactor(factor)) {
+ return {
+ operator,
+ args: [
+ factor,
+ valuesExpr.listExpr?.elements?.map(
+ (constant) => constant.constExpr?.stringValue ?? ""
+ ) ?? [],
+ ],
+ };
+ }
+
+ throw new Error(`cannot resolve expr ${JSON.stringify(expr)}`);
+};
+
+const emptySimpleExpr = (): ConditionGroupExpr => {
+ return {
+ operator: LogicalOperatorList[0],
+ args: [],
+ };
+};
diff --git a/frontend/src/plugins/cel/logic/validate.ts b/frontend/src/plugins/cel/logic/validate.ts
new file mode 100644
index 0000000000..3574463399
--- /dev/null
+++ b/frontend/src/plugins/cel/logic/validate.ts
@@ -0,0 +1,78 @@
+import { isNumber } from "lodash-es";
+import {
+ ConditionExpr,
+ ConditionGroupExpr,
+ isEqualityExpr,
+ isNumberFactor,
+ isStringFactor,
+ SimpleExpr,
+} from "../types";
+import {
+ isCollectionExpr,
+ isConditionExpr,
+ isConditionGroupExpr,
+ isCompareExpr,
+ isStringExpr,
+} from "../types";
+
+const validateString = (str: any): boolean => {
+ if (typeof str !== "string") return false;
+ return str.trim().length > 0;
+};
+const validateNumber = (num: any): boolean => {
+ return isNumber(num);
+};
+const validateArrayValues = (
+ array: any,
+ predicate: (value: any) => boolean
+): boolean => {
+ if (!Array.isArray(array)) return false;
+ if (array.length === 0) return false;
+ return array.every(predicate);
+};
+const validateStringArray = (array: any) => {
+ return validateArrayValues(array, validateString);
+};
+const validateNumberArray = (array: any) => {
+ return validateArrayValues(array, validateNumber);
+};
+
+export const validateSimpleExpr = (expr: SimpleExpr): boolean => {
+ const validateCondition = (condition: ConditionExpr): boolean => {
+ if (condition.args.length !== 2) {
+ // All condition expressions' args need to be [factor, value(s)] format.
+ return false;
+ }
+ if (isEqualityExpr(condition)) {
+ const [factor, value] = condition.args;
+ if (isStringFactor(factor)) return validateString(value);
+ if (isNumberFactor(factor)) return validateNumber(value);
+ }
+ if (isCompareExpr(condition)) {
+ const value = condition.args[1];
+ return isNumber(value);
+ }
+ if (isCollectionExpr(condition)) {
+ const [factor, values] = condition.args;
+ if (isStringFactor(factor)) return validateStringArray(values);
+ if (isNumberFactor(factor)) return validateNumberArray(values);
+ }
+ if (isStringExpr(condition)) {
+ const value = condition.args[1];
+ return validateString(value);
+ }
+ // unknown condition expr type
+ return false;
+ };
+ const validateConditionGroup = (group: ConditionGroupExpr): boolean => {
+ const { args } = group;
+ if (args.length === 0) return false;
+ return args.every(validate);
+ };
+ const validate = (expr: SimpleExpr): boolean => {
+ if (isConditionGroupExpr(expr)) return validateConditionGroup(expr);
+ if (isConditionExpr(expr)) return validateCondition(expr);
+ throw new Error(`unsupported expr '${JSON.stringify(expr)}'`);
+ };
+ return validate(expr);
+};
diff --git a/frontend/src/plugins/cel/types/factor.ts b/frontend/src/plugins/cel/types/factor.ts
new file mode 100644
index 0000000000..48d108c89c
--- /dev/null
+++ b/frontend/src/plugins/cel/types/factor.ts
@@ -0,0 +1,39 @@
+import { uniq, without } from "lodash-es";
+
+export const NumberFactorList = ["affected_rows", "risk", "source"] as const;
+export type NumberFactor = typeof NumberFactorList[number];
+
+export const StringFactorList = [
+ "environment_id", // using `environment.resource_id`
+ "project_id", // using `project.resource_id`
+ "database_name",
+ "db_engine",
+ "sql_type",
+] as const;
+export type StringFactor = typeof StringFactorList[number];
+
+export const HighLevelFactorList = ["risk", "source"] as const;
+export type HighLevelFactor = typeof HighLevelFactorList[number];
+
+export type Factor = NumberFactor | StringFactor | HighLevelFactor;
+
+export const FactorList = {
+ DDL: uniq([...HighLevelFactorList, ...StringFactorList]),
+ DML: uniq([...HighLevelFactorList, ...NumberFactorList, ...StringFactorList]),
+ CreateDatabase: without(
+ [...HighLevelFactorList, ...StringFactorList],
+ "sql_type"
+ ),
+};
+
+export const isHighLevelFactor = (
+ factor: string
+): factor is HighLevelFactor => {
+ return HighLevelFactorList.includes(factor as HighLevelFactor);
+};
+export const isStringFactor = (factor: string): factor is StringFactor => {
+ return StringFactorList.includes(factor as StringFactor);
+};
+export const isNumberFactor = (factor: string): factor is NumberFactor => {
+ return NumberFactorList.includes(factor as NumberFactor);
+};
diff --git a/frontend/src/plugins/cel/types/index.ts b/frontend/src/plugins/cel/types/index.ts
new file mode 100644
index 0000000000..f61814c335
--- /dev/null
+++ b/frontend/src/plugins/cel/types/index.ts
@@ -0,0 +1,36 @@
+/*
+ We define the factors we support in 2 dimensions
+ - Operator Type
+ - equality: ==, !=
+ - compare: <, <=, >, >=
+ - collection: @in
+ - string: contains, matches, startsWith, endsWith
+ - Value Type
+ - number, string
+
+ e.g,
+ - "insert_rows" is a factor.
+ - Its value type is `number`.
+ - It supports these operators
+ - ==, !=
+ - <, <=, >, >=
+ - "risk" is a factor.
+ - Its value type is `number`,
+ aka pre-defined constants HIGH=300, MODERATE=200, LOW=100.
+ - It supports these operators
+ - ==, != {one_of (HIGH, MODERATE, LOW)}
+ - @in [array_of (HIGH, MODERATE, LOW)]
+ - "environment" is a factor, but more complicated.
+ - Its value type is `string`.
+ - It supports these operators
+ - ==, != {environment_resource_id}
+ - @in [array_of_environment_resource_id]
+ - contains, matches, startsWith, endsWith
+ - When using string operators, "environment" indicates an environment's
+ display name rather than its resource_id.
+*/
+
+export * from "./factor";
+export * from "./operator";
+export * from "./values";
+export * from "./simple";
diff --git a/frontend/src/plugins/cel/types/operator.ts b/frontend/src/plugins/cel/types/operator.ts
new file mode 100644
index 0000000000..12918dcdc1
--- /dev/null
+++ b/frontend/src/plugins/cel/types/operator.ts
@@ -0,0 +1,86 @@
+import { uniq } from "lodash-es";
+import { Factor } from "./factor";
+
+export const LogicalOperatorList = ["_&&_", "_||_"] as const;
+export type LogicalOperator = typeof LogicalOperatorList[number];
+
+export const EqualityOperatorList = ["_==_", "_!=_"] as const;
+export type EqualityOperator = typeof EqualityOperatorList[number];
+
+export const CompareOperatorList = ["_<_", "_<=_", "_>=_", "_>_"] as const;
+export type CompareOperator = typeof CompareOperatorList[number];
+
+export const CollectionOperatorList = ["@in"] as const;
+export type CollectionOperator = typeof CollectionOperatorList[number];
+
+export const StringOperatorList = [
+ "contains",
+ "matches",
+ "startsWith",
+ "endsWith",
+] as const;
+export type StringOperator = typeof StringOperatorList[number];
+
+export type ConditionOperator =
+ | EqualityOperator
+ | CompareOperator
+ | CollectionOperator
+ | StringOperator;
+export type Operator = LogicalOperator | ConditionOperator;
+
+export const isLogicalOperator = (op: Operator): op is LogicalOperator => {
+ return LogicalOperatorList.includes(op as LogicalOperator);
+};
+export const isEqualityOperator = (op: Operator): op is EqualityOperator => {
+ return EqualityOperatorList.includes(op as EqualityOperator);
+};
+export const isCompareOperator = (op: Operator): op is CompareOperator => {
+ return CompareOperatorList.includes(op as CompareOperator);
+};
+export const isCollectionOperator = (
+ op: Operator
+): op is CollectionOperator => {
+ return CollectionOperatorList.includes(op as CollectionOperator);
+};
+export const isStringOperator = (op: Operator): op is StringOperator => {
+ return StringOperatorList.includes(op as StringOperator);
+};
+
+/// Define supported operators for each factor
+export const OperatorList: Record<Factor, Operator[]> = {
+ affected_rows: uniq([...EqualityOperatorList, ...CompareOperatorList]),
+
+ risk: uniq([...EqualityOperatorList, ...CollectionOperatorList]),
+ source: uniq([...EqualityOperatorList, ...CollectionOperatorList]),
+
+ environment_id: uniq([...EqualityOperatorList, ...CollectionOperatorList]),
+ project_id: uniq([
+ ...EqualityOperatorList,
+ ...CollectionOperatorList,
+ ...StringOperatorList,
+ ]),
+ database_name: uniq([
+ ...EqualityOperatorList,
+ ...CollectionOperatorList,
+ ...StringOperatorList,
+ ]),
+ db_engine: uniq([
+ ...EqualityOperatorList,
+ ...CollectionOperatorList,
+ ...StringOperatorList,
+ ]),
+ sql_type: uniq([
+ ...EqualityOperatorList,
+ ...CollectionOperatorList,
+ ...StringOperatorList,
+ ]),
+};
+
+export const getOperatorListByFactor = (factor: Factor) => {
+ const list = OperatorList[factor];
+ if (!list) {
+ console.warn(`unsupported factor '${factor}'`);
+ return [];
+ }
+ return list;
+};
diff --git a/frontend/src/plugins/cel/types/simple.ts b/frontend/src/plugins/cel/types/simple.ts
new file mode 100644
index 0000000000..b794bfba2c
--- /dev/null
+++ b/frontend/src/plugins/cel/types/simple.ts
@@ -0,0 +1,82 @@
+/// Define a simplified version (less nested) of CEL Expr.
+/// Convenient for local editing.
+
+import { NumberFactor, StringFactor } from "./factor";
+import {
+ type LogicalOperator,
+ type EqualityOperator,
+ type CompareOperator,
+ type StringOperator,
+ type CollectionOperator,
+ isStringOperator,
+ isCollectionOperator,
+ isLogicalOperator,
+ isCompareOperator,
+ isEqualityOperator,
+} from "./operator";
+
+export type EqualityExpr = {
+ operator: EqualityOperator;
+ args: [StringFactor | NumberFactor, string | number];
+};
+
+export type CompareExpr = {
+ operator: CompareOperator;
+ args: [NumberFactor, number];
+};
+
+export type CollectionExpr = {
+ operator: CollectionOperator;
+ args: [StringFactor | NumberFactor, string[] | number[]];
+};
+
+export type StringExpr = {
+ operator: StringOperator;
+ args: [StringFactor, string];
+};
+
+export type ConditionExpr =
+ | EqualityExpr
+ | CompareExpr
+ | CollectionExpr
+ | StringExpr;
+
+export type LogicalExpr = {
+ operator: LogicalOperator;
+ args: (ConditionExpr | ConditionGroupExpr)[];
+};
+
+export type ConditionGroupExpr = LogicalExpr;
+
+export type SimpleExpr = ConditionExpr | ConditionGroupExpr;
+
+export const isConditionGroupExpr = (
+ expr: SimpleExpr
+): expr is ConditionGroupExpr => {
+ return isLogicalOperator(expr.operator);
+};
+
+export const isEqualityExpr = (expr: SimpleExpr): expr is EqualityExpr => {
+ return isEqualityOperator(expr.operator);
+};
+
+export const isCompareExpr = (expr: SimpleExpr): expr is CompareExpr => {
+ return isCompareOperator(expr.operator);
+};
+
+export const isCollectionExpr = (expr: SimpleExpr): expr is CollectionExpr => {
+ return isCollectionOperator(expr.operator);
+};
+
+export const isStringExpr = (expr: SimpleExpr): expr is StringExpr => {
+ return isStringOperator(expr.operator);
+};
+
+export const isConditionExpr = (expr: SimpleExpr): expr is ConditionExpr => {
+ return (
+ isEqualityExpr(expr) ||
+ isCompareExpr(expr) ||
+ isCollectionExpr(expr) ||
+ isStringExpr(expr)
+ );
+};
diff --git a/frontend/src/plugins/cel/types/values.ts b/frontend/src/plugins/cel/types/values.ts
new file mode 100644
index 0000000000..4c6c7cfd96
--- /dev/null
+++ b/frontend/src/plugins/cel/types/values.ts
@@ -0,0 +1,39 @@
+export const SQLTypeList = {
+ DDL: [
+ "CREATE",
+ "CREATE_INDEX",
+ "CREATE_VIEW",
+ "CREATE_SEQUENCE",
+ "CREATE_TABLE",
+ "CREATE_SELECT",
+ "CREATE_FUNCTION",
+ "CREATE_PROCEDURE",
+ "DROP",
+ "DROP_INDEX",
+ "DROP_VIEW",
+ "DROP_TABLE",
+ "DROP_FUNCTION",
+ "DROP_PROCEDURE",
+ "ALTER",
+ "ALTER_INDEX",
+ "ALTER_VIEW",
+ "ALTER_TABLE",
+ "ALTER_SEQUENCE",
+ "ALTER_FUNCTION",
+ "ALTER_PROCEDURE",
+ "TRUNCATE",
+ "RENAME",
+ ] as const,
+ DML: [
+ "INSERT",
+ "INSERT_SELECT",
+ "REPLACE",
+ "REPLACE_INTO",
+ "UPDATE",
+ "DELETE",
+ "MERGE",
+ ] as const,
+} as const;
+
+export type SQLTypeDDL = typeof SQLTypeList.DDL[number];
+export type SQLTypeDML = typeof SQLTypeList.DML[number];
diff --git a/frontend/src/plugins/i18n.ts b/frontend/src/plugins/i18n.ts
index 6bc07c581d..5d65f2fab6 100644
--- a/frontend/src/plugins/i18n.ts
+++ b/frontend/src/plugins/i18n.ts
@@ -71,6 +71,8 @@ const i18n = createI18n({
// @ts-ignore
export const t = i18n.global.t;
+export const te = i18n.global.te;
+
export const curLocale = i18n.global.locale;
const install = (app: App) => {
diff --git a/frontend/src/router/index.ts b/frontend/src/router/index.ts
index 5bee562d14..72e0a8aab1 100644
--- a/frontend/src/router/index.ts
+++ b/frontend/src/router/index.ts
@@ -408,6 +408,14 @@ const routes: Array<RouteRecordRaw> = [
import("../views/SettingWorkspaceAccessControl.vue"),
props: true,
},
+ {
+ path: "risk-center",
+ name: "setting.workspace.risk-center",
+ meta: { title: () => t("custom-approval.risk.risk-center") },
+ component: () =>
+ import("../views/SettingWorkspaceRiskCenter.vue"),
+ props: true,
+ },
{
path: "gitops",
name: "setting.workspace.gitops",
@@ -1028,8 +1036,12 @@ router.beforeEach((to, from, next) => {
to.name === PASSWORD_RESET_MODULE ||
to.name === PASSWORD_FORGOT_MODULE
) {
- useTabStore().reset();
- useConversationStore().reset();
+ try {
+ useTabStore().reset();
+ useConversationStore().reset();
+ } catch {
+ // nothing
+ }
if (isLoggedIn) {
if (typeof to.query.redirect === "string") {
location.replace(to.query.redirect);
diff --git a/frontend/src/store/modules/index.ts b/frontend/src/store/modules/index.ts
index f9015971ef..91a66c0fc7 100644
--- a/frontend/src/store/modules/index.ts
+++ b/frontend/src/store/modules/index.ts
@@ -46,3 +46,4 @@ export * from "./schemaEditor";
export * from "./dbSchema";
export * from "./idp";
export * from "./user";
+export * from "./risk";
diff --git a/frontend/src/store/modules/risk.ts b/frontend/src/store/modules/risk.ts
new file mode 100644
index 0000000000..6f8484989e
--- /dev/null
+++ b/frontend/src/store/modules/risk.ts
@@ -0,0 +1,58 @@
+import { ref } from "vue";
+import { defineStore } from "pinia";
+
+import { riskServiceClient } from "@/grpcweb";
+import { Risk } from "@/types/proto/v1/risk_service";
+
+export const useRiskStore = defineStore("tab", () => {
+ const riskList = ref<Risk[]>([]);
+
+ const fetchRiskList = async () => {
+ const response = await riskServiceClient.listRisks({
+ pageSize: 100,
+ });
+ riskList.value = response.risks;
+ return riskList.value;
+ };
+
+ const upsertRisk = async (risk: Risk) => {
+ const existedRisk = riskList.value.find((r) => r.name === risk.name);
+ if (existedRisk) {
+ // update
+ const updated = await riskServiceClient.updateRisk({
+ risk,
+ updateMask: [
+ "risk.title",
+ "risk.level",
+ "risk.active",
+ "risk.expression",
+ ],
+ });
+ Object.assign(existedRisk, updated);
+ } else {
+ // create
+ const created = await riskServiceClient.createRisk({
+ risk,
+ });
+ Object.assign(risk, created);
+ riskList.value.push(risk);
+ }
+ };
+
+ const deleteRisk = async (risk: Risk) => {
+ await riskServiceClient.deleteRisk({
+ name: risk.name,
+ });
+ const index = riskList.value.findIndex((r) => r.name === risk.name);
+ if (index >= 0) {
+ riskList.value.splice(index, 1);
+ }
+ };
+
+ return {
+ riskList,
+ fetchRiskList,
+ upsertRisk,
+ deleteRisk,
+ };
+});
diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.ts
index 44234754d7..688cd228be 100644
--- a/frontend/src/types/index.ts
+++ b/frontend/src/types/index.ts
@@ -49,3 +49,4 @@ export * from "./onboardingGuide";
export * from "./schemaEditor";
export * from "./externalApproval";
export * from "./mfa";
+export * from "./risk";
diff --git a/frontend/src/types/instance.ts b/frontend/src/types/instance.ts
index 6e9d4594ae..7a7d48244d 100644
--- a/frontend/src/types/instance.ts
+++ b/frontend/src/types/instance.ts
@@ -10,19 +10,22 @@ import {
import { Engine } from "./proto/v1/common";
import { VCSPushEvent } from "./vcs";
-export type EngineType =
- | "CLICKHOUSE"
- | "MYSQL"
- | "POSTGRES"
- | "SNOWFLAKE"
- | "TIDB"
- | "MONGODB"
- | "SPANNER"
- | "REDIS"
- | "ORACLE"
- | "MSSQL"
- | "REDSHIFT"
- | "MARIADB";
+export const EngineTypeList = [
+ "CLICKHOUSE",
+ "MYSQL",
+ "POSTGRES",
+ "SNOWFLAKE",
+ "TIDB",
+ "MONGODB",
+ "SPANNER",
+ "REDIS",
+ "ORACLE",
+ "MSSQL",
+ "REDSHIFT",
+ "MARIADB",
+] as const;
+
+export type EngineType = typeof EngineTypeList[number];
export function convertEngineType(type: EngineType): Engine {
switch (type) {
diff --git a/frontend/src/types/risk.ts b/frontend/src/types/risk.ts
new file mode 100644
index 0000000000..09c80e4f1d
--- /dev/null
+++ b/frontend/src/types/risk.ts
@@ -0,0 +1,18 @@
+import { Risk_Source } from "./proto/v1/risk_service";
+
+export const PresetRiskLevel = {
+ HIGH: 300,
+ MODERATE: 200,
+ LOW: 100,
+};
+export const PresetRiskLevelList = [
+ { name: "HIGH", level: PresetRiskLevel.HIGH },
+ { name: "MODERATE", level: PresetRiskLevel.MODERATE },
+ { name: "LOW", level: PresetRiskLevel.LOW },
+];
+
+export const SupportedSourceList = [
+ Risk_Source.DDL,
+ Risk_Source.DML,
+ Risk_Source.CREATE_DATABASE,
+];
diff --git a/frontend/src/utils/role.ts b/frontend/src/utils/role.ts
index c5315fe5b5..ecae35ee46 100644
--- a/frontend/src/utils/role.ts
+++ b/frontend/src/utils/role.ts
@@ -20,6 +20,7 @@ export type WorkspacePermissionType =
| "bb.permission.workspace.manage-general"
| "bb.permission.workspace.manage-sensitive-data"
| "bb.permission.workspace.manage-access-control"
+ | "bb.permission.workspace.manage-custom-approval"
| "bb.permission.workspace.manage-subscription"
// Can execute admininstrive queries such as "SHOW PROCESSLIST"
| "bb.permission.workspace.admin-sql-editor"
@@ -48,6 +49,7 @@ export const WORKSPACE_PERMISSION_MATRIX: Map<
["bb.permission.workspace.manage-sso", [false, false, true]],
["bb.permission.workspace.manage-sensitive-data", [false, true, true]],
["bb.permission.workspace.manage-access-control", [false, true, true]],
+ ["bb.permission.workspace.manage-custom-approval", [false, false, true]],
["bb.permission.workspace.manage-subscription", [false, false, true]],
["bb.permission.workspace.admin-sql-editor", [false, true, true]],
["bb.permission.workspace.audit-log", [false, true, true]],
diff --git a/frontend/src/utils/types.ts b/frontend/src/utils/types.ts
index 0c48050e72..821d762d4f 100644
--- a/frontend/src/utils/types.ts
+++ b/frontend/src/utils/types.ts
@@ -1,3 +1,7 @@
+import type { StyleValue } from "vue";
+
export type VueClass = string | Record<string, unknown> | Array<VueClass>;
+export type VueStyle = StyleValue;
+
export type ExtractPromiseType<T> = T extends Promise<infer U> ? U : unknown;
diff --git a/frontend/src/views/SettingSidebar.vue b/frontend/src/views/SettingSidebar.vue
index b0de6df767..4a5c45c5b6 100644
--- a/frontend/src/views/SettingSidebar.vue
+++ b/frontend/src/views/SettingSidebar.vue
@@ -83,6 +83,12 @@
class="outline-item group w-full flex items-center pl-11 pr-2 py-2"
>{{ $t("sql-review.title") }}</router-link
>
+ <router-link
+ to="/setting/risk-center"
+ class="outline-item group w-full flex items-center truncate pl-11 pr-2 py-2"
+ >
+ {{ $t("custom-approval.risk.risk-center") }}
+ </router-link>
<router-link
v-if="showSensitiveDataItem"
to="/setting/sensitive-data"
diff --git a/frontend/src/views/SettingWorkspaceRiskCenter.vue b/frontend/src/views/SettingWorkspaceRiskCenter.vue
new file mode 100644
index 0000000000..ee79ff5355
--- /dev/null
+++ b/frontend/src/views/SettingWorkspaceRiskCenter.vue
@@ -0,0 +1,76 @@
+<template>
+ <div class="w-full mt-4 space-y-4 text-sm">
+ <FeatureAttention
+ v-if="!hasCustomApprovalFeature"
+ feature="bb.feature.custom-approval"
+ :description="$t('subscription.features.bb-feature-custom-approval.desc')"
+ />
+
+ <RiskCenter v-if="state.ready" />
+ <div v-else class="w-full py-[4rem] flex justify-center items-center">
+ <BBSpin />
+ </div>
+ </div>
+
+ <RiskDialog />
+
+ <FeatureModal
+ v-if="state.showFeatureModal"
+ feature="bb.feature.custom-approval"
+ @cancel="state.showFeatureModal = false"
+ />
+</template>
+
+<script lang="ts" setup>
+import { computed, onMounted, reactive, ref, toRef } from "vue";
+
+import { featureToRef, useCurrentUser, useRiskStore } from "@/store";
+import { hasWorkspacePermission } from "@/utils";
+import {
+ RiskCenter,
+ RiskDialog,
+ provideRiskCenterContext,
+} from "@/components/CustomApproval/Settings";
+import { Risk_Source } from "@/types/proto/v1/risk_service";
+
+interface LocalState {
+ ready: boolean;
+ showFeatureModal: boolean;
+}
+
+const state = reactive<LocalState>({
+ ready: false,
+ showFeatureModal: false,
+});
+const hasCustomApprovalFeature = featureToRef("bb.feature.custom-approval");
+
+const currentUser = useCurrentUser();
+const allowAdmin = computed(() => {
+ return hasWorkspacePermission(
+ "bb.permission.workspace.manage-custom-approval",
+ currentUser.value.role
+ );
+});
+
+provideRiskCenterContext({
+ hasFeature: hasCustomApprovalFeature,
+ showFeatureModal: toRef(state, "showFeatureModal"),
+ allowAdmin,
+ ready: toRef(state, "ready"),
+ navigation: ref({
+ levels: new Set<number>(), // empty to "ALL"
+ search: "",
+ source: Risk_Source.SOURCE_UNSPECIFIED, // "ALL"
+ }),
+ dialog: ref(),
+});
+
+onMounted(async () => {
+ try {
+ await useRiskStore().fetchRiskList();
+ state.ready = true;
+ } catch {
+ // nothing
+ }
+});
+</script>