feat: Phase 4 - SQL AST analyzer, audit rules CRUD, Alembic, Docker (128 tests)

This commit is contained in:
logan committed 2026-05-22 13:35:35 +08:00
1 parent e45fbf3586
commit ff0a330e8a
23 files changed
+1404 -159

No files matched your search

+263 -109
View File
@@ -1,134 +1,288 @@
import { useState } from 'react';
import { Plus, Search, Edit2, Trash2, Shield, AlertTriangle, AlertCircle, Info, CheckCircle, ToggleLeft, ToggleRight, FileCode } from 'lucide-react';
import { Card, CardContent } from '@/components/ui/card';
import { auditRules, dbTypeColorMap } from '@/lib/mock';
import { useState, useEffect } from 'react';
import request from '../api/request';
const levelConfig = {
error: { icon: AlertTriangle, color: 'text-red-400 bg-red-400/10', label: '错误' },
warning: { icon: AlertCircle, color: 'text-yellow-400 bg-yellow-400/10', label: '警告' },
info: { icon: Info, color: 'text-blue-400 bg-blue-400/10', label: '提示' },
interface AuditRule {
id: number;
name: string;
description: string | null;
rule_type: string;
severity: string;
db_type: string;
pattern: string | null;
is_enabled: boolean;
message: string;
created_at: string;
updated_at: string;
}
const RULE_TYPES = [
{ value: 'syntax', label: '语法检查', color: 'bg-blue-100 text-blue-700' },
{ value: 'performance', label: '性能优化', color: 'bg-yellow-100 text-yellow-700' },
{ value: 'safety', label: '安全检查', color: 'bg-red-100 text-red-700' },
{ value: 'naming', label: '命名规范', color: 'bg-green-100 text-green-700' },
];
const SEVERITY_MAP: Record<string, { label: string; color: string }> = {
error: { label: '错误', color: 'bg-red-500 text-white' },
warning: { label: '警告', color: 'bg-yellow-500 text-white' },
info: { label: '提示', color: 'bg-blue-500 text-white' },
};
export default function AuditRulesPage() {
const [search, setSearch] = useState('');
const [levelFilter, setLevelFilter] = useState('');
const [rules, setRules] = useState(auditRules);
const filtered = rules.filter(r => {
if (levelFilter && r.level !== levelFilter) return false;
if (search && !r.name.includes(search) && !r.description.includes(search)) return false;
return true;
const [rules, setRules] = useState<AuditRule[]>([]);
const [loading, setLoading] = useState(true);
const [filter, setFilter] = useState({ rule_type: '', severity: '', is_enabled: '' });
const [showCreate, setShowCreate] = useState(false);
const [stats, setStats] = useState<any>(null);
const [form, setForm] = useState({
name: '', description: '', rule_type: 'safety', severity: 'warning',
db_type: 'mysql', pattern: '', is_enabled: true, message: '',
});
const toggleRule = (id: string) => {
setRules(prev => prev.map(r => r.id === id ? { ...r, enabled: !r.enabled } : r));
};
useEffect(() => { fetchRules(); fetchStats(); }, []);
async function fetchRules() {
try {
setLoading(true);
const params = new URLSearchParams();
if (filter.rule_type) params.set('rule_type', filter.rule_type);
if (filter.severity) params.set('severity', filter.severity);
if (filter.is_enabled !== '') params.set('is_enabled', filter.is_enabled);
const res = await request.get('/audit-rules', { params });
setRules(res.data);
} catch { /* */ } finally { setLoading(false); }
}
async function fetchStats() {
try {
const res = await request.get('/audit-rules/stats/summary');
setStats(res.data);
} catch { /* */ }
}
async function handleCreate() {
try {
await request.post('/audit-rules', form);
setShowCreate(false);
setForm({ name: '', description: '', rule_type: 'safety', severity: 'warning', db_type: 'mysql', pattern: '', is_enabled: true, message: '' });
fetchRules();
fetchStats();
} catch (err: any) {
alert(err.response?.data?.detail || '创建失败');
}
}
async function handleToggle(rule: AuditRule) {
try {
await request.post('/audit-rules/' + rule.id + '/toggle');
fetchRules();
fetchStats();
} catch { /* */ }
}
async function handleDelete(id: number) {
if (!confirm('确认删除此规则?')) return;
try {
await request.delete('/audit-rules/' + id);
fetchRules();
fetchStats();
} catch { /* */ }
}
const getTypeInfo = (type: string) => RULE_TYPES.find(t => t.value === type) || RULE_TYPES[0];
const getSeverityInfo = (sev: string) => SEVERITY_MAP[sev] || SEVERITY_MAP.info;
return (
<div className="space-y-5">
<div className="space-y-6">
{/* Header */}
<div className="flex items-center justify-between">
<div>
<h1 className="text-2xl font-semibold">SQL 审核规则</h1>
<p className="text-sm text-[var(--dg-text-secondary)] mt-1">配置 SQL 审核规则,确保数据变更安全合规</p>
</div>
<div className="flex gap-3">
<button className="flex items-center gap-2 px-4 py-2.5 bg-[var(--dg-bg-tertiary)] border border-[var(--dg-border)] rounded-lg text-sm font-medium hover:bg-[var(--dg-bg-hover)] transition-all">
<FileCode className="w-4 h-4" /> 导入规则
</button>
<button className="flex items-center gap-2 px-4 py-2.5 bg-gradient-to-r from-blue-500 to-purple-600 rounded-lg text-sm font-medium text-white hover:opacity-90 transition-opacity">
<Plus className="w-4 h-4" /> 添加规则
</button>
<h1 className="text-xl font-semibold text-gray-900">审核规则</h1>
<p className="text-sm text-gray-500 mt-1">管理 SQL 审核引擎的检查规则</p>
</div>
<button
onClick={() => setShowCreate(true)}
className="px-4 py-2 bg-blue-600 text-white rounded-lg text-sm hover:bg-blue-700"
>
新建规则
</button>
</div>
<div className="grid grid-cols-4 gap-4">
{[
{ label: '规则总数', value: rules.length, icon: Shield, color: 'text-blue-400', bg: 'bg-blue-400/10' },
{ label: '已启用', value: rules.filter(r => r.enabled).length, icon: CheckCircle, color: 'text-green-400', bg: 'bg-green-400/10' },
{ label: '错误级', value: rules.filter(r => r.level === 'error').length, icon: AlertTriangle, color: 'text-red-400', bg: 'bg-red-400/10' },
{ label: '警告级', value: rules.filter(r => r.level === 'warning').length, icon: AlertCircle, color: 'text-yellow-400', bg: 'bg-yellow-400/10' },
].map((s, i) => (
<Card key={i} className="dg-card">
<CardContent className="p-4 flex items-center gap-3">
<div className={`w-10 h-10 rounded-lg ${s.bg} flex items-center justify-center`}><s.icon className={`w-5 h-5 ${s.color}`} /></div>
<div><div className="text-2xl font-bold">{s.value}</div><div className="text-xs text-[var(--dg-text-muted)]">{s.label}</div></div>
</CardContent>
</Card>
))}
</div>
<div className="flex items-center gap-3 p-4 dg-card flex-wrap">
<div className="relative flex-1 max-w-xs">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-[var(--dg-text-muted)]" />
<input className="w-full pl-10 pr-4 py-2.5 bg-[var(--dg-bg-tertiary)] border border-[var(--dg-border)] rounded-lg text-sm placeholder:text-[var(--dg-text-muted)] focus:border-blue-400 focus:outline-none" placeholder="搜索规则名称" value={search} onChange={e => setSearch(e.target.value)} />
{/* Stats */}
{stats && (
<div className="grid grid-cols-4 gap-4">
{[
{ label: '总规则数', value: stats.total, color: 'text-gray-900' },
{ label: '已启用', value: stats.enabled, color: 'text-green-600' },
{ label: '已禁用', value: stats.disabled, color: 'text-gray-400' },
{ label: '类型', value: Object.keys(stats.by_type || {}).length, color: 'text-blue-600' },
].map(s => (
<div key={s.label} className="bg-white rounded-lg p-4 shadow-sm">
<p className="text-sm text-gray-500">{s.label}</p>
<p className={'text-2xl font-bold ' + s.color}>{s.value}</p>
</div>
))}
</div>
<select className="px-3 py-2.5 bg-[var(--dg-bg-tertiary)] border border-[var(--dg-border)] rounded-lg text-sm focus:border-blue-400 focus:outline-none" value={levelFilter} onChange={e => setLevelFilter(e.target.value)}>
)}
{/* Filters */}
<div className="flex gap-3">
<select
value={filter.rule_type}
onChange={e => setFilter({ ...filter, rule_type: e.target.value })}
className="px-3 py-2 border border-gray-200 rounded-lg text-sm"
>
<option value="">全部类型</option>
{RULE_TYPES.map(t => <option key={t.value} value={t.value}>{t.label}</option>)}
</select>
<select
value={filter.severity}
onChange={e => setFilter({ ...filter, severity: e.target.value })}
className="px-3 py-2 border border-gray-200 rounded-lg text-sm"
>
<option value="">全部级别</option>
<option value="error">错误</option>
<option value="warning">警告</option>
<option value="info">提示</option>
</select>
<select
value={filter.is_enabled}
onChange={e => setFilter({ ...filter, is_enabled: e.target.value })}
className="px-3 py-2 border border-gray-200 rounded-lg text-sm"
>
<option value="">全部状态</option>
<option value="true">已启用</option>
<option value="false">已禁用</option>
</select>
<button onClick={fetchRules} className="px-3 py-2 bg-gray-100 rounded-lg text-sm hover:bg-gray-200">
刷新
</button>
</div>
<Card className="dg-card">
<CardContent className="p-0">
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead>
<tr className="border-b border-[var(--dg-border)] bg-[var(--dg-bg-tertiary)]">
<th className="text-left px-5 py-3 font-semibold">规则ID</th>
<th className="text-left px-5 py-3 font-semibold">规则名称</th>
<th className="text-left px-5 py-3 font-semibold">级别</th>
<th className="text-left px-5 py-3 font-semibold">适用数据库</th>
<th className="text-left px-5 py-3 font-semibold">描述</th>
<th className="text-left px-5 py-3 font-semibold">状态</th>
<th className="text-left px-5 py-3 font-semibold">操作</th>
</tr>
</thead>
<tbody>
{filtered.map(rule => {
const lc = levelConfig[rule.level];
const LIcon = lc.icon;
return (
<tr key={rule.id} className={`border-b border-[var(--dg-border-light)] hover:bg-[var(--dg-bg-hover)] transition-colors ${!rule.enabled ? 'opacity-50' : ''}`}>
<td className="px-5 py-3.5 font-mono text-xs text-[var(--dg-text-secondary)]">{rule.id}</td>
<td className="px-5 py-3.5 font-medium">{rule.name}</td>
<td className="px-5 py-3.5">
<span className={`inline-flex items-center gap-1.5 px-2 py-1 rounded-md text-xs font-medium ${lc.color}`}>
<LIcon className="w-3.5 h-3.5" /> {lc.label}
</span>
</td>
<td className="px-5 py-3.5">
<div className="flex flex-wrap gap-1">
{rule.dbTypes.map(dt => (
<span key={dt} className={`inline-flex px-2 py-0.5 rounded text-[11px] font-medium ${dbTypeColorMap[dt] || ''}`}>{dt.toUpperCase()}</span>
))}
</div>
</td>
<td className="px-5 py-3.5 text-[var(--dg-text-secondary)] max-w-xs truncate">{rule.description}</td>
<td className="px-5 py-3.5">
<button onClick={() => toggleRule(rule.id)} className="transition-colors">
{rule.enabled ? (
<ToggleRight className="w-8 h-8 text-green-400" />
) : (
<ToggleLeft className="w-8 h-8 text-[var(--dg-text-muted)]" />
)}
</button>
</td>
<td className="px-5 py-3.5">
<div className="flex gap-2">
<button className="text-blue-400 hover:text-blue-300"><Edit2 className="w-4 h-4" /></button>
<button className="text-red-400 hover:text-red-300"><Trash2 className="w-4 h-4" /></button>
</div>
</td>
</tr>
);
})}
</tbody>
</table>
{/* Create Modal */}
{showCreate && (
<div className="fixed inset-0 bg-black/30 flex items-center justify-center z-50">
<div className="bg-white rounded-xl shadow-xl w-full max-w-lg p-6">
<h2 className="text-lg font-semibold mb-4">新建审核规则</h2>
<div className="space-y-3">
<input
placeholder="规则名称"
value={form.name}
onChange={e => setForm({ ...form, name: e.target.value })}
className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm"
/>
<textarea
placeholder="描述(可选)"
value={form.description}
onChange={e => setForm({ ...form, description: e.target.value })}
className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm"
rows={2}
/>
<div className="grid grid-cols-2 gap-3">
<select
value={form.rule_type}
onChange={e => setForm({ ...form, rule_type: e.target.value })}
className="px-3 py-2 border border-gray-200 rounded-lg text-sm"
>
{RULE_TYPES.map(t => <option key={t.value} value={t.value}>{t.label}</option>)}
</select>
<select
value={form.severity}
onChange={e => setForm({ ...form, severity: e.target.value })}
className="px-3 py-2 border border-gray-200 rounded-lg text-sm"
>
<option value="error">错误</option>
<option value="warning">警告</option>
<option value="info">提示</option>
</select>
</div>
<input
placeholder="匹配模式(正则表达式,可选)"
value={form.pattern}
onChange={e => setForm({ ...form, pattern: e.target.value })}
className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm font-mono"
/>
<input
placeholder="提示消息"
value={form.message}
onChange={e => setForm({ ...form, message: e.target.value })}
className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm"
/>
</div>
<div className="flex justify-end gap-3 mt-5">
<button onClick={() => setShowCreate(false)} className="px-4 py-2 text-sm text-gray-600 hover:bg-gray-100 rounded-lg">
取消
</button>
<button onClick={handleCreate} className="px-4 py-2 bg-blue-600 text-white rounded-lg text-sm hover:bg-blue-700">
创建
</button>
</div>
</div>
</CardContent>
</Card>
</div>
)}
{/* Rules Table */}
<div className="bg-white rounded-lg shadow-sm overflow-hidden">
{loading ? (
<div className="p-8 text-center text-gray-400">加载中...</div>
) : rules.length === 0 ? (
<div className="p-8 text-center text-gray-400">暂无规则,点击"新建规则"添加</div>
) : (
<table className="w-full">
<thead>
<tr className="bg-gray-50 text-left text-xs text-gray-500">
<th className="px-4 py-3">规则名称</th>
<th className="px-4 py-3">类型</th>
<th className="px-4 py-3">级别</th>
<th className="px-4 py-3">提示消息</th>
<th className="px-4 py-3">状态</th>
<th className="px-4 py-3 text-right">操作</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-100">
{rules.map(rule => {
const typeInfo = getTypeInfo(rule.rule_type);
const sevInfo = getSeverityInfo(rule.severity);
return (
<tr key={rule.id} className="hover:bg-gray-50">
<td className="px-4 py-3">
<div>
<p className="font-medium text-sm text-gray-900">{rule.name}</p>
{rule.description && <p className="text-xs text-gray-400 mt-0.5">{rule.description}</p>}
</div>
</td>
<td className="px-4 py-3">
<span className={'px-2 py-0.5 rounded text-xs ' + typeInfo.color}>{typeInfo.label}</span>
</td>
<td className="px-4 py-3">
<span className={'px-2 py-0.5 rounded text-xs ' + sevInfo.color}>{sevInfo.label}</span>
</td>
<td className="px-4 py-3 text-sm text-gray-600 max-w-xs truncate">{rule.message}</td>
<td className="px-4 py-3">
<button
onClick={() => handleToggle(rule)}
className={'px-2 py-1 rounded text-xs ' + (
rule.is_enabled ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-400'
)}
>
{rule.is_enabled ? '启用' : '禁用'}
</button>
</td>
<td className="px-4 py-3 text-right">
<button
onClick={() => handleDelete(rule.id)}
className="text-xs text-red-500 hover:text-red-700"
>
删除
</button>
</td>
</tr>
);
})}
</tbody>
</table>
)}
</div>
</div>
);
}