feat: P0生产加固 — 认证安全+操作审计+错误提示

P0-1 认证安全:
- JWT secret 改为环境变量配置, 未设置则随机生成(重启失效)
- 新增 LoginRateLimitMiddleware: 5次/分钟登录频率限制(滑动窗口)
- 429 响应 + 前端 toast 提示

P0-2 操作审计日志:
- 新增 OperationLog 模型 (user/username/action/resource/detail/ip)
- 新增 AuditLogMiddleware 自动记录 POST/PUT/DELETE/PATCH 操作
- 新增 GET /audit-logs API (分页/过滤/统计)
- 前端 AuditLogsPage 对接真实 API (字段/路径修正)

P0-3 实例密码加密:
- 已确认 crypto.py AES-256-GCM 加密存储, 无需修改

P1 前端错误提示:
- 新增 useToast hook + ToastContainer 组件
- request.ts 拦截器: 4xx/5xx 错误 toast 显示后端 detail 信息
- 422 验证错误提取第一条 msg
- 网络失败显示通用提示

1182 tests passed
This commit is contained in:
logan committed 2026-05-25 12:57:59 +08:00
1 parent 0576b253e4
commit 344c519209
15 files changed
+510 -97

No files matched your search

+48 -44
View File
@@ -17,11 +17,10 @@ interface AuditLog {
user_id: number;
username: string;
action: string;
target_type: string;
target_id: number | null;
resource_type: string;
resource_id: number | null;
detail: string | null;
ip_address: string | null;
result_status: 'success' | 'failed' | 'warning';
created_at: string | null;
}
@@ -35,29 +34,27 @@ interface AuditLogResponse {
/* ───────── Constants ───────── */
const ACTION_COLORS: Record<string, string> = {
CREATE_TICKET: 'bg-blue-500/15 text-blue-400',
REVIEW_TICKET: 'bg-yellow-500/15 text-yellow-400',
EXECUTE_TICKET: 'bg-green-500/15 text-green-400',
CREATE_INSTANCE: 'bg-purple-500/15 text-purple-400',
DELETE_INSTANCE: 'bg-red-500/15 text-red-400',
CREATE_USER: 'bg-indigo-500/15 text-indigo-400',
DELETE_USER: 'bg-red-500/15 text-red-400',
QUERY: 'bg-cyan-500/15 text-cyan-400',
LOGIN: 'bg-emerald-500/15 text-emerald-400',
LOGOUT: 'bg-[var(--dg-text-muted)]/15 text-[var(--dg-text-muted)]',
create: 'bg-blue-500/15 text-blue-400',
approve: 'bg-yellow-500/15 text-yellow-400',
execute: 'bg-green-500/15 text-green-400',
update: 'bg-purple-500/15 text-purple-400',
delete: 'bg-red-500/15 text-red-400',
login: 'bg-emerald-500/15 text-emerald-400',
login_failed: 'bg-red-500/15 text-red-400',
cancel: 'bg-orange-500/15 text-orange-400',
reject: 'bg-red-500/15 text-red-400',
};
const ACTION_LABELS: Record<string, string> = {
CREATE_TICKET: '创建工单',
REVIEW_TICKET: '审批工单',
EXECUTE_TICKET: '执行工单',
CREATE_INSTANCE: '创建实例',
DELETE_INSTANCE: '删除实例',
CREATE_USER: '创建用户',
DELETE_USER: '删除用户',
QUERY: '执行查询',
LOGIN: '登录',
LOGOUT: '登出',
create: '创建',
update: '更新',
delete: '删除',
approve: '审批',
execute: '执行',
cancel: '取消',
reject: '拒绝',
login: '登录',
login_failed: '登录失败',
};
const STATUS_CONFIG: Record<string, { icon: React.ElementType; color: string; label: string }> = {
@@ -70,8 +67,12 @@ const TARGET_ICONS: Record<string, React.ElementType> = {
ticket: FileText,
instance: Globe,
user: User,
query: Search,
system: AlertTriangle,
auth: User,
audit_rule: Search,
notification: AlertTriangle,
workflow: FileText,
system_setting: AlertTriangle,
other: FileText,
};
const CHART_COLORS = ['#6366f1', '#a855f7', '#ec4899', '#f43f5e', '#f97316', '#eab308', '#22c55e', '#06b6d4', '#3b82f6'];
@@ -81,9 +82,9 @@ const CHART_COLORS = ['#6366f1', '#a855f7', '#ec4899', '#f43f5e', '#f97316', '#e
function exportLogsToCSV(logs: AuditLog[]) {
const headers = ['ID', '操作人', '操作类型', '目标类型', '目标ID', '详情', 'IP地址', '结果', '时间'];
const rows = logs.map(l => [
l.id, l.username, ACTION_LABELS[l.action] || l.action, l.target_type,
l.target_id || '', l.detail || '', l.ip_address || '',
l.result_status === 'success' ? '成功' : l.result_status === 'failed' ? '失败' : '警告',
l.id, l.username, ACTION_LABELS[l.action] || l.action, l.resource_type,
l.resource_id || '', l.detail || '', l.ip_address || '',
l.action.includes('fail') || l.action === 'reject' ? '失败' : '成功',
l.created_at || '',
]);
const csv = [headers, ...rows].map(r => r.map(c => `"${String(c).replace(/"/g, '""')}"`).join(',')).join('\n');
@@ -123,7 +124,7 @@ export default function AuditLogsPage() {
try {
const params = new URLSearchParams({ page: String(page), page_size: String(pageSize) });
if (filterAction) params.set('action', filterAction);
const res = await request.get(`/audit/logs?${params}`);
const res = await request.get(`/audit-logs?${params}`);
const data = (res?.data ?? res ?? {}) as AuditLogResponse;
const items = data.items || [];
setLogs(items);
@@ -141,8 +142,8 @@ export default function AuditLogsPage() {
// Client-side filtering for advanced filters
const filteredLogs = useMemo(() => {
return logs.filter(log => {
if (filterTarget && log.target_type !== filterTarget) return false;
if (filterStatus && log.result_status !== filterStatus) return false;
if (filterTarget && log.resource_type !== filterTarget) return false;
if (filterStatus && log.action.includes('fail') !== (filterStatus === 'failed')) return false;
if (filterDateRange && log.created_at) {
const days = Math.floor((Date.now() - new Date(log.created_at).getTime()) / 86400000);
if (filterDateRange === '1d' && days > 1) return false;
@@ -184,12 +185,14 @@ export default function AuditLogsPage() {
}, [logs]);
const statusDistribution = useMemo(() => {
const map: Record<string, number> = { success: 0, failed: 0, warning: 0 };
logs.forEach(l => { map[l.result_status] = (map[l.result_status] || 0) + 1; });
let success = 0, failed = 0;
logs.forEach(l => {
if (l.action.includes('fail') || l.action === 'reject') failed++;
else success++;
});
return [
{ name: '成功', value: map.success, color: '#22c55e' },
{ name: '失败', value: map.failed, color: '#f43f5e' },
{ name: '警告', value: map.warning, color: '#eab308' },
{ name: '成功', value: success, color: '#22c55e' },
{ name: '失败', value: failed, color: '#f43f5e' },
];
}, [logs]);
@@ -349,8 +352,9 @@ export default function AuditLogsPage() {
<option value="ticket">工单</option>
<option value="instance">实例</option>
<option value="user">用户</option>
<option value="query">查询</option>
<option value="system">系统</option>
<option value="auth">认证</option>
<option value="workflow">审批流</option>
<option value="notification">通知</option>
</select>
{/* Status filter */}
@@ -362,7 +366,6 @@ export default function AuditLogsPage() {
<option value="">全部结果</option>
<option value="success">成功</option>
<option value="failed">失败</option>
<option value="warning">警告</option>
</select>
{/* Date range */}
@@ -436,9 +439,10 @@ export default function AuditLogsPage() {
) : (
paginatedLogs.map(log => {
const isExpanded = expandedId === log.id;
const statusConfig = STATUS_CONFIG[log.result_status] || STATUS_CONFIG.success;
const isFailed = log.action.includes('fail') || log.action === 'reject';
const statusConfig = isFailed ? STATUS_CONFIG.failed : STATUS_CONFIG.success;
const StatusIcon = statusConfig.icon;
const TargetIcon = TARGET_ICONS[log.target_type] || FileText;
const TargetIcon = TARGET_ICONS[log.resource_type] || FileText;
return (
<Fragment key={log.id}>
<tr
@@ -467,8 +471,8 @@ export default function AuditLogsPage() {
<td className="px-4 py-3">
<div className="flex items-center gap-1.5">
<TargetIcon className="w-3.5 h-3.5 text-[var(--dg-text-muted)]" />
<span className="text-[var(--dg-text-secondary)]">{log.target_type}</span>
{log.target_id && <span className="text-[var(--dg-text-muted)] text-xs">#{log.target_id}</span>}
<span className="text-[var(--dg-text-secondary)]">{log.resource_type}</span>
{log.resource_id && <span className="text-[var(--dg-text-muted)] text-xs">#{log.resource_id}</span>}
</div>
</td>
<td className="px-4 py-3 text-[var(--dg-text-secondary)] text-xs font-mono">
@@ -505,7 +509,7 @@ export default function AuditLogsPage() {
</div>
<div>
<div className="text-xs text-[var(--dg-text-muted)] mb-1">目标ID</div>
<div className="text-sm font-mono">{log.target_id || 'N/A'}</div>
<div className="text-sm font-mono">{log.resource_id || 'N/A'}</div>
</div>
<div>
<div className="text-xs text-[var(--dg-text-muted)] mb-1">时间</div>