Files
monkey-ai-web/src/components/settings/DataSecuritySetting.jsx
T

1389 lines
49 KiB
React
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useEffectEvent } from '../../hooks/common/useEffectEvent';
import React, { useEffect, useRef, useState } from 'react';
import {
Banner,
Button,
Card,
Descriptions,
Form,
Modal,
Popconfirm,
Space,
Spin,
Table,
Tag,
Tabs,
TabPane,
TextArea,
Typography,
} from '@/components/ui';
import { API, isRoot, showError, showSuccess } from '../../helpers';
import { useTranslation } from 'react-i18next';
const MODE_OPTIONS = [
{ value: 'detect_only', label: '仅检测告警' },
{ value: 'standard', label: '标准脱敏(可逆占位符)' },
{ value: 'strict', label: '严格不可逆' },
{ value: 'block', label: '阻断模式' },
];
const FAILURE_OPTIONS = [
{ value: 'fail_closed', label: 'fail_closed(失败即拒绝,推荐)' },
{ value: 'fail_open', label: 'fail_open(失败透传,高风险)' },
];
const MULTIMODAL_OPTIONS = [
{ value: 'warn', label: 'warn(放行+对文本脱敏+告警,默认)' },
{ value: 'reject', label: 'reject(拒绝含图片/音频请求)' },
{
value: 'passthrough_with_audit',
label: 'passthrough_with_audit(放行+审计)',
},
];
const SENSITIVE_OPTIONS = [
{ value: 'allow', label: 'allow(标准脱敏后放行,用户无感,默认)' },
{
value: 'require_consent',
label: 'require_consent(需用户单独同意,需同意后端)',
},
{ value: 'block_sensitive', label: 'block_sensitive(直接拒绝)' },
{ value: 'strict_anonymize', label: 'strict_anonymize(强制不可逆)' },
];
const PII_LEVEL_OPTIONS = [
{ value: 'general', label: '一般个人信息' },
{ value: 'sensitive', label: '敏感个人信息' },
];
const piiLevelTag = (v, t) =>
v === 'sensitive' ? (
<Tag color='red'>{t('敏感')}</Tag>
) : (
<Tag color='blue'>{t('一般')}</Tag>
);
const enabledTag = (v, t) =>
v ? <Tag color='green'>{t('启用')}</Tag> : <Tag>{t('停用')}</Tag>;
const fmtTime = (v) => (v ? new Date(v * 1000).toLocaleString() : '-');
const ORG_CHANGE_TYPES = new Set([
'org_config',
'org_config_delete',
'org_self_config',
'org_self_config_delete',
]);
const ORG_DELETE_TYPES = new Set([
'org_config_delete',
'org_self_config_delete',
]);
const ORG_POLICY_FIELDS = [
['mode', '脱敏模式'],
['failure_strategy', '失败策略'],
['multimodal_strategy', '多模态策略'],
['sensitive_strategy', '敏感信息策略'],
['anti_evasion', '反绕过检测'],
];
const parseChangePayload = (payload) => {
try {
return JSON.parse(payload || '{}');
} catch {
return null;
}
};
export default function DataSecuritySetting() {
const { t } = useTranslation();
const tOptions = (options) =>
options.map((o) => ({ ...o, label: t(o.label) }));
const [loading, setLoading] = useState(false);
// 初始值须与后端默认一致(setting/desensitize.go),否则 loadConfig 失败时
// 页面展示的是不真实的状态、点保存还会把这些值写进去。
const [config, setConfig] = useState({
enabled: false,
mode: 'standard',
failure_strategy: 'fail_closed',
multimodal_strategy: 'warn',
sensitive_strategy: 'allow',
egress_enforcement: false,
approval_required: false,
anti_evasion: false,
});
const [configLoaded, setConfigLoaded] = useState(false);
const [builtinRules, setBuiltinRules] = useState([]);
const [customRules, setCustomRules] = useState([]);
// 企业私有规则监督视图(企业自助维护;平台只读 + 紧急删除止血)
const [orgRules, setOrgRules] = useState([]);
const [audits, setAudits] = useState([]);
const [auditPageSize, setAuditPageSize] = useState(20);
const [auditPage, setAuditPage] = useState(1);
const [auditTotal, setAuditTotal] = useState(0);
const [hitLogs, setHitLogs] = useState([]);
const [hitLogPageSize, setHitLogPageSize] = useState(20);
const [hitLogPage, setHitLogPage] = useState(1);
const [hitLogTotal, setHitLogTotal] = useState(0);
const [changeRequests, setChangeRequests] = useState([]);
const [changeReqPageSize, setChangeReqPageSize] = useState(20);
const [changeReqPage, setChangeReqPage] = useState(1);
const [changeReqTotal, setChangeReqTotal] = useState(0);
const [metrics, setMetrics] = useState(null);
const [testText, setTestText] = useState(
'我的邮箱 zhang@abc.com,手机 13800138000',
);
const [testResult, setTestResult] = useState(null);
// 规则编辑弹窗
const [ruleModalVisible, setRuleModalVisible] = useState(false);
const [editingRule, setEditingRule] = useState(null); // null=新增
// 提交防重(R41):慢网络下双击「确定」会连发两次 POST 创建两条同名规则;
// 开启二级审批时则产生两条待审批请求。企业端 OrgDsRules 已有同款守卫。
const [ruleSubmitting, setRuleSubmitting] = useState(false);
const formApiRef = useRef();
const ruleFormApiRef = useRef();
// 后端约定:业务失败返回 200 + {success:false, message}——加载失败必须显式提示,
// 否则表格静默为空、配置页永远停在"加载中"。
// 网络类失败必须 catch:否则 configLoaded 永远 false、保存按钮死锁在
// "配置加载中…"且页面无重试入口(R39 修复)。
const [configLoadError, setConfigLoadError] = useState(false);
const loadConfig = async () => {
setConfigLoadError(false);
try {
const res = await API.get('/api/desensitize/config');
if (res.data?.success) {
setConfig(res.data.data);
setConfigLoaded(true);
formApiRef.current?.setValues(res.data.data);
} else {
setConfigLoadError(true);
showError(res.data?.message || t('加载脱敏配置失败,请刷新重试'));
}
} catch (err) {
// axios 错误已由全局拦截器弹出提示,这里只记录错误态供重试横幅使用
setConfigLoadError(true);
}
};
const loadRules = async () => {
const res = await API.get('/api/desensitize/rules');
if (res.data?.success) {
setBuiltinRules(res.data.data?.builtin || []);
setCustomRules(res.data.data?.custom || []);
setOrgRules(res.data.data?.org_custom || []);
} else {
showError(res.data?.message || t('加载规则失败'));
}
};
const [auditLoading, setAuditLoading] = useState(false);
const [hitLogLoading, setHitLogLoading] = useState(false);
const [changeReqLoading, setChangeReqLoading] = useState(false);
const loadAudits = async (page = 1, size = auditPageSize) => {
setAuditLoading(true);
try {
const res = await API.get(
`/api/desensitize/config-audit?page=${page}&page_size=${size}`,
);
if (res.data?.success) {
setAudits(res.data.data?.items || []);
setAuditTotal(res.data.data?.total || 0);
setAuditPage(page);
} else {
showError(res.data?.message || t('加载配置审计失败'));
}
} catch (err) {
showError(err.message || t('加载配置审计失败'));
} finally {
setAuditLoading(false);
}
};
const loadHitLogs = async (page = 1, size = hitLogPageSize) => {
setHitLogLoading(true);
try {
const res = await API.get(
`/api/desensitize/logs?page=${page}&page_size=${size}`,
);
if (res.data?.success) {
setHitLogs(res.data.data?.items || []);
setHitLogTotal(res.data.data?.total || 0);
setHitLogPage(page);
} else {
showError(res.data?.message || t('加载命中审计失败'));
}
} catch (err) {
showError(err.message || t('加载命中审计失败'));
} finally {
setHitLogLoading(false);
}
};
const loadChangeRequests = async (page = 1, size = changeReqPageSize) => {
setChangeReqLoading(true);
try {
const res = await API.get(
`/api/desensitize/change-requests?page=${page}&page_size=${size}`,
);
if (res.data?.success) {
setChangeRequests(res.data.data?.items || []);
setChangeReqTotal(res.data.data?.total || 0);
setChangeReqPage(page);
} else {
showError(res.data?.message || t('加载变更审批列表失败'));
}
} catch (err) {
showError(err.message || t('加载变更审批列表失败'));
} finally {
setChangeReqLoading(false);
}
};
// 监控指标失败必须显式呈现 '-' 而非 0:安全巡检语境下"待审批 0 / 敏感命中 0"
// 是有含义的结论,不能由失败态冒充(与企业侧命中审计同一原则,R39 修复)。
const [metricsError, setMetricsError] = useState(false);
const loadMetrics = async () => {
try {
const res = await API.get('/api/desensitize/metrics?since_hours=24');
if (res.data?.success) {
setMetrics(res.data.data);
setMetricsError(false);
} else {
setMetricsError(true);
showError(res.data?.message || t('加载监控指标失败'));
}
} catch (err) {
setMetricsError(true);
}
};
const [killStatus, setKillStatus] = useState(null);
const loadKillStatus = async () => {
const res = await API.get('/api/desensitize/killswitch');
if (res.data?.success) setKillStatus(res.data.data);
else showError(res.data?.message || t('加载熔断状态失败'));
};
// 租户定制(强合规)
const [orgConfigs, setOrgConfigs] = useState([]);
const [orgModalVisible, setOrgModalVisible] = useState(false);
const [editingOrgId, setEditingOrgId] = useState(null); // null=新增;编辑时锁定 org_id 防止改号产生孤儿行
const [orgSubmitting, setOrgSubmitting] = useState(false); // 提交防重(R41,同规则弹窗)
const orgFormApiRef = useRef();
const loadOrgConfigs = async () => {
const res = await API.get('/api/desensitize/org-config');
if (res.data?.success) setOrgConfigs(res.data.data || []);
else showError(res.data?.message || t('加载企业覆盖列表失败'));
};
const openCreateOrgConfig = () => {
setEditingOrgId(null);
setOrgModalVisible(true);
setTimeout(
() =>
orgFormApiRef.current?.setValues({
org_id: undefined,
mode: '',
failure_strategy: '',
multimodal_strategy: '',
sensitive_strategy: '',
anti_evasion: '',
}),
0,
);
};
const openEditOrgConfig = (row) => {
setEditingOrgId(row.org_id);
setOrgModalVisible(true);
setTimeout(() => orgFormApiRef.current?.setValues(row), 0);
};
const submitOrgConfig = async () => {
if (orgSubmitting) return;
let values;
try {
values = await orgFormApiRef.current?.validate();
} catch (e) {
return;
}
setOrgSubmitting(true);
try {
const res = await API.put('/api/desensitize/org-config', {
...values,
org_id: Number(editingOrgId ?? values.org_id),
});
if (res.data?.success) {
showSuccess(res.data?.message || t('保存成功'));
setOrgModalVisible(false);
loadOrgConfigs();
loadChangeRequests(); // 开启二级审批时会进入待审批队列
} else {
showError(res.data?.message || t('保存失败'));
}
} finally {
setOrgSubmitting(false);
}
};
const deleteOrgConfig = async (orgId) => {
const res = await API.delete(`/api/desensitize/org-config/${orgId}`);
if (res.data?.success) {
showSuccess(res.data?.message || t('删除成功'));
loadOrgConfigs();
loadChangeRequests(); // 开启二级审批时会进入待审批队列
} else {
showError(res.data?.message || t('删除失败'));
}
};
const toggleKillSwitch = async (action) => {
const res = await API.post('/api/desensitize/killswitch', {
action,
scope: 'global',
ttl_seconds: 1800,
});
if (res.data?.success) {
showSuccess(res.data?.message || t('操作成功'));
loadKillStatus();
loadMetrics();
} else {
showError(res.data?.message || t('操作失败'));
}
};
const reloadAll = () => {
loadConfig();
loadRules();
loadAudits();
loadHitLogs();
loadChangeRequests();
loadMetrics();
loadKillStatus();
loadOrgConfigs();
};
const onMount = useEffectEvent(() => {
reloadAll();
});
useEffect(() => onMount(), [onMount]);
const onSave = async () => {
if (!configLoaded) {
showError(
t('配置尚未加载成功,禁止保存(避免覆盖线上配置),请刷新重试'),
);
return;
}
setLoading(true);
try {
const res = await API.put('/api/desensitize/config', config);
if (res.data?.success) {
showSuccess(res.data?.message || t('保存成功'));
// 直接生效路径回读生效值;审批路径回读后表单恢复为线上值,避免"看似已生效"的错觉。
loadConfig();
loadAudits();
loadChangeRequests();
} else {
showError(res.data?.message || t('保存失败'));
}
} catch (e) {
showError(t('保存失败'));
} finally {
setLoading(false);
}
};
const onTest = async () => {
const res = await API.post('/api/desensitize/test', { text: testText });
if (res.data?.success) setTestResult(res.data.data);
else showError(res.data?.message || t('测试失败'));
};
// ---- 自定义规则 CRUD ----
const openCreateRule = () => {
setEditingRule(null);
setRuleModalVisible(true);
setTimeout(() => {
ruleFormApiRef.current?.setValues({
name: '',
category: '',
pattern: '',
pii_level: 'general',
enabled: true,
});
}, 0);
};
const openEditRule = (rule) => {
setEditingRule(rule);
setRuleModalVisible(true);
setTimeout(() => ruleFormApiRef.current?.setValues(rule), 0);
};
const submitRule = async () => {
if (ruleSubmitting) return;
let values;
try {
values = await ruleFormApiRef.current?.validate();
} catch (e) {
return;
}
setRuleSubmitting(true);
try {
const isEdit = !!editingRule;
const url = isEdit
? `/api/desensitize/rules/${editingRule.id}`
: '/api/desensitize/rules';
const res = isEdit
? await API.put(url, values)
: await API.post(url, values);
if (res.data?.success) {
showSuccess(res.data?.message || t('保存成功'));
setRuleModalVisible(false);
loadRules();
loadChangeRequests();
} else {
showError(res.data?.message || t('保存失败'));
}
} finally {
setRuleSubmitting(false);
}
};
const deleteRule = async (rule) => {
const res = await API.delete(`/api/desensitize/rules/${rule.id}`);
if (res.data?.success) {
showSuccess(res.data?.message || t('删除成功'));
loadRules();
loadChangeRequests();
} else {
showError(res.data?.message || t('删除失败'));
}
};
// ---- 审批 ----
const reviewRequest = async (id, action) => {
const res = await API.post(
`/api/desensitize/change-requests/${id}/${action}`,
);
if (res.data?.success) {
showSuccess(res.data?.message || t('操作成功'));
loadChangeRequests(changeReqPage);
loadConfig();
loadRules();
loadOrgConfigs(); // 变更请求也可能是企业覆盖的增删改
} else {
showError(res.data?.message || t('操作失败'));
}
};
const builtinColumns = [
{ title: t('规则名'), dataIndex: 'name' },
{ title: t('类别'), dataIndex: 'category' },
{
title: t('PII 分级'),
dataIndex: 'pii_level',
render: (v) => piiLevelTag(v, t),
},
{ title: t('启用'), dataIndex: 'enabled', render: (v) => enabledTag(v, t) },
];
const customColumns = [
{ title: 'ID', dataIndex: 'id', width: 70 },
{ title: t('规则名'), dataIndex: 'name' },
{ title: t('类别'), dataIndex: 'category' },
{
title: t('正则'),
dataIndex: 'pattern',
render: (v) => (
<Typography.Text code style={{ wordBreak: 'break-all' }}>
{v}
</Typography.Text>
),
},
{
title: t('PII 分级'),
dataIndex: 'pii_level',
render: (v) => piiLevelTag(v, t),
},
{ title: t('启用'), dataIndex: 'enabled', render: (v) => enabledTag(v, t) },
{
title: t('操作'),
render: (_, rule) => (
<Space>
<Button onClick={() => openEditRule(rule)} type='link' size='small'>
{t('编辑')}
</Button>
<Popconfirm
title={t('确认删除该规则?')}
onConfirm={() => deleteRule(rule)}
>
<Button type='link' size='small' danger>
{t('删除')}
</Button>
</Popconfirm>
</Space>
),
},
];
const auditColumns = [
{ title: t('时间'), dataIndex: 'created_at', render: fmtTime },
{ title: t('操作人'), dataIndex: 'operator_name' },
{ title: t('配置项'), dataIndex: 'target' },
{ title: t('旧值'), dataIndex: 'old_value' },
{ title: t('新值'), dataIndex: 'new_value' },
{ title: 'IP', dataIndex: 'ip' },
];
const hitLogColumns = [
{ title: t('时间'), dataIndex: 'created_at', render: fmtTime },
{ title: t('用户'), dataIndex: 'user_id' },
{ title: t('模型'), dataIndex: 'model' },
{ title: t('命中数'), dataIndex: 'hit_count' },
{
title: t('敏感 PII'),
dataIndex: 'has_sensitive_pii',
render: (v) =>
v ? <Tag color='red'>{t('是')}</Tag> : <Tag>{t('否')}</Tag>,
},
{
title: t('豁免'),
dataIndex: 'bypassed',
render: (v) => (v ? <Tag color='orange'>{t('是')}</Tag> : '-'),
},
{
title: 'fail_open',
dataIndex: 'fail_open',
render: (v) => (v ? <Tag color='red'>fail_open</Tag> : '-'),
},
{ title: t('原文长度'), dataIndex: 'content_length' },
{ title: t('耗时(ms)'), dataIndex: 'desensitize_ms' },
];
const STATUS_TAG = {
pending: <Tag color='amber'>{t('待审批')}</Tag>,
approved: <Tag color='green'>{t('已通过')}</Tag>,
rejected: <Tag color='grey'>{t('已驳回')}</Tag>,
};
const formatOrgPolicyValue = (field, value) => {
if (value === '' || value === undefined || value === null) {
const inherited = config[field];
const inheritedText =
field === 'anti_evasion'
? inherited
? t('开启')
: t('关闭')
: inherited || '-';
return t('继承({{value}})', { value: inheritedText });
}
if (field === 'anti_evasion') {
return String(value) === 'true' ? t('开启') : t('关闭');
}
return String(value);
};
const renderChangeContent = (request) => {
const payload = parseChangePayload(request.payload);
if (!payload) {
return <Tag color='red'>{t('变更内容 JSON 无效')}</Tag>;
}
if (ORG_CHANGE_TYPES.has(request.req_type)) {
const orgId = Number(payload.org_id || request.target_id);
const current = orgConfigs.find((item) => item.org_id === orgId) || {};
const deleting = ORG_DELETE_TYPES.has(request.req_type);
return (
<div className='text-xs leading-5 min-w-[320px]'>
<div className='font-medium mb-1'>OrgId: {orgId}</div>
{ORG_POLICY_FIELDS.map(([field, label]) => {
const currentValue = formatOrgPolicyValue(field, current[field]);
const requestedValue = formatOrgPolicyValue(
field,
deleting ? '' : payload[field],
);
return (
<div key={field}>
<span className='text-gray-500'>{t(label)}:</span>
<span>{currentValue}</span>
<span className='mx-1'>→</span>
<span className='font-medium'>{requestedValue}</span>
</div>
);
})}
</div>
);
}
return (
<Typography.Text
size='small'
className='font-mono whitespace-pre-wrap break-all'
>
{JSON.stringify(payload, null, 2)}
</Typography.Text>
);
};
const changeReqColumns = [
{ title: 'ID', dataIndex: 'id', width: 70 },
{ title: t('类型'), dataIndex: 'req_type' },
{ title: t('摘要'), dataIndex: 'summary' },
{
title: t('变更内容(当前 → 申请)'),
dataIndex: 'payload',
render: (_, request) => renderChangeContent(request),
},
{ title: t('提交人'), dataIndex: 'maker_name' },
{
title: t('状态'),
dataIndex: 'status',
render: (v) => STATUS_TAG[v] || v,
},
{ title: t('审批人'), dataIndex: 'checker_name', render: (v) => v || '-' },
{ title: t('提交时间'), dataIndex: 'created_at', render: fmtTime },
{
title: t('操作'),
render: (_, r) =>
r.status === 'pending' ? (
<Space>
<Popconfirm
title={t(
'请核对表格中的当前值与申请值。确认审批通过并立即生效?(不能审批自己提交的变更)',
)}
onConfirm={() => reviewRequest(r.id, 'approve')}
>
<Button type='link' size='small'>
{t('通过')}
</Button>
</Popconfirm>
<Popconfirm
title={t('确认驳回?')}
onConfirm={() => reviewRequest(r.id, 'reject')}
>
<Button type='link' size='small' danger>
{t('驳回')}
</Button>
</Popconfirm>
</Space>
) : (
'-'
),
},
];
const m = metrics?.runtime || {};
const w = metrics?.window_stats || {};
// 监控失败/未加载显示 '-':0 是有含义的巡检结论,不能由失败态冒充(R39 修复)
const mval = (v) => (metricsError || !metrics ? '-' : (v ?? 0));
return (
<Spin spinning={loading}>
<Banner
type='info'
closeIcon={null}
description={t(
'本功能基于规则匹配,无法识别所有类型的敏感信息(如图像内容、详细地址、外文姓名、未知格式的密钥等)。请勿单独依赖本功能作为合规保障。',
)}
style={{ marginBottom: 16 }}
/>
<Tabs type='line'>
<TabPane tab={t('总开关与策略')} itemKey='config'>
<Card style={{ marginTop: 12 }}>
{configLoadError && (
<Banner
type='danger'
closeIcon={null}
description={
<Space>
{t('配置加载失败,为防止误覆盖线上配置,保存已禁用。')}
<Button
size='small'
type='danger'
theme='light'
onClick={loadConfig}
>
{t('重试')}
</Button>
</Space>
}
style={{ marginBottom: 12 }}
/>
)}
{config.approval_required && (
<Banner
type='info'
closeIcon={null}
description={t(
'已开启二级审批:配置与规则的变更需另一名管理员审批后才生效,提交后请到「变更审批」页处理。',
)}
style={{ marginBottom: 12 }}
/>
)}
<Form
labelPosition='left'
labelWidth={180}
getFormApi={(api) => (formApiRef.current = api)}
>
<Form.Switch
field='enabled'
label={t('启用脱敏总开关')}
initValue={config.enabled}
onChange={(v) => setConfig({ ...config, enabled: v })}
/>
<Form.Select
field='mode'
label={t('工作模式')}
optionList={tOptions(MODE_OPTIONS)}
initValue={config.mode}
onChange={(v) => setConfig({ ...config, mode: v })}
style={{ width: 360 }}
/>
<Form.Select
field='failure_strategy'
label={t('失败策略')}
optionList={tOptions(FAILURE_OPTIONS)}
initValue={config.failure_strategy}
onChange={(v) => setConfig({ ...config, failure_strategy: v })}
style={{ width: 360 }}
/>
<Form.Select
field='multimodal_strategy'
label={t('多模态请求策略')}
optionList={tOptions(MULTIMODAL_OPTIONS)}
initValue={config.multimodal_strategy}
onChange={(v) =>
setConfig({ ...config, multimodal_strategy: v })
}
style={{ width: 360 }}
/>
<Form.Select
field='sensitive_strategy'
label={t('敏感 PII 策略')}
optionList={tOptions(SENSITIVE_OPTIONS)}
initValue={config.sensitive_strategy}
onChange={(v) =>
setConfig({ ...config, sensitive_strategy: v })
}
style={{ width: 360 }}
/>
<Form.Switch
field='egress_enforcement'
label={t('出境强制兜底(fail-closed)')}
extraText={t(
'⚠️ 开启后,未被脱敏标记的出境请求一律拒绝。请在确认全协议已脱敏后再开启,否则可能拒绝 Realtime / 未覆盖出口的请求。',
)}
initValue={config.egress_enforcement}
onChange={(v) =>
setConfig({ ...config, egress_enforcement: v })
}
/>
<Form.Switch
field='approval_required'
label={t('配置变更二级审批')}
extraText={t(
'开启后,脱敏配置与自定义规则的增删改需另一名管理员审批后才生效,降低单人误关/恶意关闭脱敏的风险。',
)}
initValue={config.approval_required}
onChange={(v) => setConfig({ ...config, approval_required: v })}
/>
<Form.Switch
field='anti_evasion'
label={t('反绕过检测')}
extraText={t(
'开启后,对敏感 PII(身份证/银行卡)额外做 base64/hex 解码重扫 + 全角规范化重扫,拦截编码变形偷渡。仅扫带校验位的敏感规则、有文本长度上限,性能可控;尽力而为,不保证 100%。',
)}
initValue={config.anti_evasion}
onChange={(v) => setConfig({ ...config, anti_evasion: v })}
/>
</Form>
<Button
theme='solid'
onClick={onSave}
disabled={!configLoaded || configLoadError}
style={{ marginTop: 12 }}
>
{configLoaded ? t('保存配置') : t('配置加载中…')}
</Button>
</Card>
</TabPane>
<TabPane tab={t('规则管理')} itemKey='rules'>
<Card title={t('内置规则(只读)')} style={{ marginTop: 12 }}>
<Table
columns={builtinColumns}
dataSource={builtinRules}
pagination={false}
rowKey='id'
/>
</Card>
<Card
title={t('自定义规则')}
style={{ marginTop: 12 }}
headerExtraContent={
<Button theme='solid' onClick={openCreateRule}>
{t('新增规则')}
</Button>
}
>
<Banner
type='info'
closeIcon={null}
description={t(
'自定义规则使用 RE2 正则(线性时间、抗 ReDoS)。正则不得超过 500 字符、不得匹配空串。命中后等同内置规则参与脱敏。',
)}
style={{ marginBottom: 12 }}
/>
<Table
columns={customColumns}
dataSource={customRules}
pagination={false}
rowKey='id'
scroll={{ x: 'max(100%, 900px)' }}
/>
</Card>
<Card title={t('企业私有规则')} style={{ marginTop: 12 }}>
<Banner
type='info'
closeIcon={null}
description={t(
'各企业在企业中心「数据安全」自助维护,仅对该企业流量生效。平台保留紧急删除权(止血通道,删除会同步记入该企业的变更留痕);修改规则内容请由企业自行操作。关闭企业的 data_security 授权也会在约 1 分钟内卸载其全部规则。',
)}
style={{ marginBottom: 12 }}
/>
<Table
columns={[
{ title: 'OrgId', dataIndex: 'org_id', width: 90 },
{ title: 'ID', dataIndex: 'id', width: 70 },
{ title: t('规则名'), dataIndex: 'name' },
{ title: t('类别'), dataIndex: 'category' },
{
title: t('正则'),
dataIndex: 'pattern',
render: (v) => (
<Typography.Text code style={{ wordBreak: 'break-all' }}>
{v}
</Typography.Text>
),
},
{
title: t('PII 分级'),
dataIndex: 'pii_level',
render: (v) => piiLevelTag(v, t),
},
{
title: t('启用'),
dataIndex: 'enabled',
render: (v) => enabledTag(v, t),
},
{
title: t('操作'),
render: (_, rule) => (
<Popconfirm
title={t(
'确认紧急删除该企业私有规则?将同步记入该企业的变更留痕。',
)}
onConfirm={() => deleteRule(rule)}
>
<Button type='link' size='small' danger>
{t('删除')}
</Button>
</Popconfirm>
),
},
]}
dataSource={orgRules}
pagination={false}
rowKey='id'
scroll={{ x: 'max(100%, 960px)' }}
empty={
<span style={{ color: 'var(--ui-color-text-2)' }}>
{t('暂无企业私有规则')}
</span>
}
/>
</Card>
</TabPane>
<TabPane tab={t('脱敏测试')} itemKey='test'>
<Card style={{ marginTop: 12 }}>
<TextArea
value={testText}
onChange={setTestText}
autosize={{ minRows: 3, maxRows: 8 }}
placeholder={t('输入样本文本(样本不入库,仅内存处理)')}
/>
<Button theme='solid' onClick={onTest} style={{ marginTop: 12 }}>
{t('测试脱敏效果')}
</Button>
{testResult && (
<div style={{ marginTop: 16 }}>
<Typography.Title heading={6}>
{t('脱敏后')}{' '}
{testResult.mode && (
<Tag color='blue'>
{t('当前模式')}: {testResult.mode}
</Tag>
)}
{(testResult.mode === 'detect_only' ||
testResult.mode === 'block') && (
<Tag color='amber'>
{testResult.mode === 'block'
? t('block 模式下命中即拒绝,以下为命中演示')
: t('detect_only 模式下不改写,以下为命中演示')}
</Tag>
)}
</Typography.Title>
<Typography.Paragraph
copyable
style={{
background: 'var(--ui-color-fill-0)',
padding: 12,
borderRadius: 6,
}}
>
{testResult.desensitized}
</Typography.Paragraph>
<div>
{t('命中')} {testResult.hit_count}{' '}
{(testResult.hits || []).map((h, i) => (
<Tag
key={i}
color={h.pii_level === 'sensitive' ? 'red' : 'blue'}
style={{ marginRight: 4 }}
>
{h.category} → {h.token}
</Tag>
))}
</div>
</div>
)}
</Card>
</TabPane>
<TabPane tab={t('变更审批')} itemKey='approval'>
<Card style={{ marginTop: 12 }}>
<Banner
type='info'
closeIcon={null}
description={t(
'开启二级审批后,配置与规则变更在此排队。审批人必须与提交人不同(职责分离)。',
)}
style={{ marginBottom: 12 }}
/>
<Table
columns={changeReqColumns}
dataSource={changeRequests}
loading={changeReqLoading}
rowKey='id'
pagination={{
currentPage: changeReqPage,
pageSize: changeReqPageSize,
total: changeReqTotal,
onPageChange: (p) => loadChangeRequests(p),
onPageSizeChange: (size) => {
setChangeReqPageSize(size);
loadChangeRequests(1, size);
},
}}
/>
</Card>
</TabPane>
<TabPane tab={t('监控')} itemKey='metrics'>
<Card
title={t(
'运行时指标(当前节点、自进程启动累计;多节点部署请以下方 DB 聚合为准)',
)}
style={{ marginTop: 12 }}
headerExtraContent={
<Button onClick={loadMetrics}>{t('刷新')}</Button>
}
>
<Descriptions
align='center'
data={[
{ key: t('处理请求数'), value: mval(m.processed) },
{ key: t('已脱敏'), value: mval(m.replaced) },
{ key: t('旁路'), value: mval(m.bypassed) },
{ key: t('fail_closed 拒绝'), value: mval(m.fail_closed) },
{ key: t('fail_open 触发'), value: mval(m.fail_open) },
{ key: t('block 拦截'), value: mval(m.blocked_by_mode) },
{ key: t('敏感 PII 硬拦'), value: mval(m.sensitive_blocked) },
{ key: t('多模态拒绝'), value: mval(m.multimodal_reject) },
{
key: t('出境兜底拦截(P0)'),
value:
metricsError || !metrics ? (
'-'
) : (m.egress_blocked ?? 0) > 0 ? (
<Tag color='red'>{m.egress_blocked}</Tag>
) : (
0
),
},
{ key: t('反绕过命中'), value: mval(m.evasion_detected) },
{
key: t('占位符残留(模型改写)'),
value:
metricsError || !metrics ? (
'-'
) : (m.residual_token ?? 0) > 0 ? (
<Tag color='amber'>{m.residual_token}</Tag>
) : (
0
),
},
{
key: t('活跃 Session(应≈0)'),
value:
metricsError || !metrics ? (
'-'
) : (m.active_sessions ?? 0) > 50 ? (
<Tag color='red'>{m.active_sessions}</Tag>
) : (
(m.active_sessions ?? 0)
),
},
{
key: 'Kill Switch',
value:
metricsError || !metrics ? (
'-'
) : m.kill_switch_active ? (
<Tag color='red'>{t('已熔断')}</Tag>
) : (
<Tag color='green'>{t('正常')}</Tag>
),
},
]}
/>
</Card>
<Card
title={t('近 24 小时命中统计(DB 聚合)')}
style={{ marginTop: 12 }}
>
<Descriptions
align='center'
data={[
{ key: t('审计记录数'), value: mval(w.total) },
{ key: t('命中敏感 PII 请求'), value: mval(w.sensitive_hits) },
{ key: t('旁路请求'), value: mval(w.bypassed_count) },
{ key: t('fail_open 请求'), value: mval(w.fail_open_count) },
{ key: t('命中总次数'), value: mval(w.total_hits) },
{
key: t('待审批变更'),
value: mval(metrics?.pending_change_requests),
},
{
key: t('自定义规则数'),
value: mval(metrics?.custom_rule_count),
},
{
key: t('企业私有规则数'),
value: mval(metrics?.org_rule_count),
},
]}
/>
</Card>
<Card title={t('紧急熔断(Kill Switch)')} style={{ marginTop: 12 }}>
<Banner
type={killStatus?.global_killed ? 'danger' : 'info'}
closeIcon={null}
description={
killStatus?.global_killed
? t(
'⚠️ 脱敏已被全局熔断!上游请求当前不脱敏。请尽快排查并解除。',
)
: t(
'紧急熔断走 Redis 快速通道(秒级生效,绕过 60s 配置轮询),激活后默认 30 分钟自动恢复。仅在脱敏引擎异常导致线上故障时使用。',
)
}
style={{ marginBottom: 12 }}
/>
{!killStatus?.redis_enabled && (
<Banner
type='warning'
closeIcon={null}
description={t('未启用 Redis,紧急熔断不可用。')}
style={{ marginBottom: 12 }}
/>
)}
<Space>
<Tag
color={killStatus?.global_killed ? 'red' : 'green'}
size='large'
>
{killStatus?.global_killed ? t('已熔断') : t('正常')}
</Tag>
<Popconfirm
title={t('确认全局熔断脱敏 30 分钟?期间上游请求不脱敏。')}
onConfirm={() => toggleKillSwitch('activate')}
>
<Button
type='danger'
disabled={
!isRoot() ||
!killStatus?.redis_enabled ||
killStatus?.global_killed
}
>
{isRoot() ? t('激活熔断') : t('激活熔断(仅超级管理员)')}
</Button>
</Popconfirm>
<Button
theme='solid'
disabled={
!killStatus?.redis_enabled || !killStatus?.global_killed
}
onClick={() => toggleKillSwitch('deactivate')}
>
{t('解除熔断')}
</Button>
</Space>
</Card>
</TabPane>
<TabPane tab={t('租户定制')} itemKey='orgconfig'>
<Card
title={t('企业级策略覆盖(强合规租户)')}
style={{ marginTop: 12 }}
headerExtraContent={
<Button theme='solid' onClick={openCreateOrgConfig}>
{t('新增覆盖')}
</Button>
}
>
<Banner
type='info'
closeIcon={null}
description={t(
'为指定企业(OrgId)单独设置脱敏策略覆盖(如阻断模式、敏感直接拒绝、开启反绕过),不影响其它租户。留空字段=继承全局。总开关仍由全局把控。开启二级审批后,企业覆盖的增删改同样需另一名管理员审批。',
)}
style={{ marginBottom: 12 }}
/>
<Table
columns={[
{ title: 'OrgId', dataIndex: 'org_id', width: 90 },
{
title: t('工作模式'),
dataIndex: 'mode',
render: (v) => v || t('继承'),
},
{
title: t('失败策略'),
dataIndex: 'failure_strategy',
render: (v) => v || t('继承'),
},
{
title: t('多模态'),
dataIndex: 'multimodal_strategy',
render: (v) => v || t('继承'),
},
{
title: t('敏感策略'),
dataIndex: 'sensitive_strategy',
render: (v) => v || t('继承'),
},
{
title: t('反绕过'),
dataIndex: 'anti_evasion',
render: (v) => (v ? v : t('继承')),
},
{
title: t('操作'),
render: (_, row) => (
<Space>
<Button
onClick={() => openEditOrgConfig(row)}
type='link'
size='small'
>
{t('编辑')}
</Button>
<Popconfirm
title={t('确认删除该企业覆盖(回到继承全局)?')}
onConfirm={() => deleteOrgConfig(row.org_id)}
>
<Button type='link' size='small' danger>
{t('删除')}
</Button>
</Popconfirm>
</Space>
),
},
]}
dataSource={orgConfigs}
pagination={false}
rowKey='org_id'
/>
</Card>
</TabPane>
<TabPane tab={t('命中审计')} itemKey='hitlog'>
<Card style={{ marginTop: 12 }}>
<Banner
type='info'
closeIcon={null}
description={t(
'命中审计仅记录规则命中统计与元信息,绝不存储原文。',
)}
style={{ marginBottom: 12 }}
/>
<Table
columns={hitLogColumns}
dataSource={hitLogs}
loading={hitLogLoading}
rowKey='id'
pagination={{
currentPage: hitLogPage,
pageSize: hitLogPageSize,
total: hitLogTotal,
onPageChange: (p) => loadHitLogs(p),
onPageSizeChange: (size) => {
setHitLogPageSize(size);
loadHitLogs(1, size);
},
}}
/>
</Card>
</TabPane>
<TabPane tab={t('配置变更审计')} itemKey='audit'>
<Card style={{ marginTop: 12 }}>
<Table
columns={auditColumns}
dataSource={audits}
loading={auditLoading}
rowKey='id'
pagination={{
currentPage: auditPage,
pageSize: auditPageSize,
total: auditTotal,
onPageChange: (p) => loadAudits(p),
onPageSizeChange: (size) => {
setAuditPageSize(size);
loadAudits(1, size);
},
}}
/>
</Card>
</TabPane>
</Tabs>
<Modal
title={editingRule ? t('编辑自定义规则') : t('新增自定义规则')}
visible={ruleModalVisible}
onOk={submitRule}
onCancel={() => setRuleModalVisible(false)}
maskClosable={false}
okButtonProps={{ loading: ruleSubmitting }}
>
<Form
getFormApi={(api) => (ruleFormApiRef.current = api)}
labelPosition='top'
>
<Form.Input
field='name'
label={t('规则名称')}
rules={[{ required: true, message: t('规则名称不能为空') }]}
/>
<Form.Input
field='category'
label={t('类别标签(可选,默认 CUSTOM)')}
/>
<Form.Input
field='pattern'
label={t('正则表达式(RE2)')}
placeholder={t('例如') + ' EMP[0-9]{6}'}
rules={[{ required: true, message: t('正则不能为空') }]}
/>
<Form.Select
field='pii_level'
label={t('PII 分级')}
optionList={tOptions(PII_LEVEL_OPTIONS)}
style={{ width: '100%' }}
/>
<Form.Switch field='enabled' label={t('启用')} />
</Form>
</Modal>
<Modal
title={t('企业级策略覆盖')}
visible={orgModalVisible}
onOk={submitOrgConfig}
onCancel={() => setOrgModalVisible(false)}
maskClosable={false}
okButtonProps={{ loading: orgSubmitting }}
>
<Form
getFormApi={(api) => (orgFormApiRef.current = api)}
labelPosition='top'
>
<Form.InputNumber
field='org_id'
label={editingOrgId ? `OrgId(${t('编辑中不可修改')})` : 'OrgId'}
min={1}
disabled={!!editingOrgId}
rules={[{ required: true, message: t('OrgId 必填且 > 0') }]}
style={{ width: '100%' }}
/>
<Form.Select
field='mode'
label={t('工作模式(留空=继承)')}
style={{ width: '100%' }}
>
<Form.Select.Option value=''>{t('继承全局')}</Form.Select.Option>
{MODE_OPTIONS.map((o) => (
<Form.Select.Option key={o.value} value={o.value}>
{t(o.label)}
</Form.Select.Option>
))}
</Form.Select>
<Form.Select
field='sensitive_strategy'
label={t('敏感策略(留空=继承)')}
style={{ width: '100%' }}
>
<Form.Select.Option value=''>{t('继承全局')}</Form.Select.Option>
{SENSITIVE_OPTIONS.map((o) => (
<Form.Select.Option key={o.value} value={o.value}>
{t(o.label)}
</Form.Select.Option>
))}
</Form.Select>
<Form.Select
field='multimodal_strategy'
label={t('多模态策略(留空=继承)')}
style={{ width: '100%' }}
>
<Form.Select.Option value=''>{t('继承全局')}</Form.Select.Option>
{MULTIMODAL_OPTIONS.map((o) => (
<Form.Select.Option key={o.value} value={o.value}>
{t(o.label)}
</Form.Select.Option>
))}
</Form.Select>
<Form.Select
field='failure_strategy'
label={t('失败策略(留空=继承)')}
style={{ width: '100%' }}
>
<Form.Select.Option value=''>{t('继承全局')}</Form.Select.Option>
{FAILURE_OPTIONS.map((o) => (
<Form.Select.Option key={o.value} value={o.value}>
{t(o.label)}
</Form.Select.Option>
))}
</Form.Select>
<Form.Select
field='anti_evasion'
label={t('反绕过(留空=继承)')}
style={{ width: '100%' }}
>
<Form.Select.Option value=''>{t('继承全局')}</Form.Select.Option>
<Form.Select.Option value='true'>{t('开启')}</Form.Select.Option>
<Form.Select.Option value='false'>{t('关闭')}</Form.Select.Option>
</Form.Select>
</Form>
</Modal>
</Spin>
);
}