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:
1 parent
0576b253e4
commit
344c519209
15 files changed
+510
-97
No files matched your search
@@ -21,6 +21,7 @@ import MongoDBDetailPage from '@/pages/MongoDBDetailPage';
|
||||
import TicketCreatePage from '@/pages/TicketCreatePage';
|
||||
import TicketDetailPage from '@/pages/TicketDetailPage';
|
||||
import InstanceGroupPage from '@/pages/InstanceGroupPage';
|
||||
import { ToastContainer } from '@/components/ToastContainer';
|
||||
|
||||
// 路由守卫:未登录跳转登录页,无权限跳转仪表盘
|
||||
function RouteGuard() {
|
||||
@@ -86,6 +87,7 @@ function App() {
|
||||
<ThemeProvider>
|
||||
<AuthProvider>
|
||||
<AppRoutes />
|
||||
<ToastContainer />
|
||||
</AuthProvider>
|
||||
</ThemeProvider>
|
||||
</BrowserRouter>
|
||||
|
||||
+15
-18
@@ -1,4 +1,5 @@
|
||||
import axios from 'axios';
|
||||
import { toast } from '@/hooks/useToast';
|
||||
|
||||
const request = axios.create({
|
||||
baseURL: '/api/v1',
|
||||
@@ -10,40 +11,36 @@ request.interceptors.request.use((config) => {
|
||||
if (token) {
|
||||
config.headers.Authorization = `Bearer ${token}`;
|
||||
}
|
||||
|
||||
// Debug logging
|
||||
console.log(
|
||||
`[API] ${config.method?.toUpperCase()} ${config.baseURL}${config.url}`,
|
||||
config.params ? 'params=' + JSON.stringify(config.params) : '',
|
||||
config.data ? 'data=' + JSON.stringify(config.data).substring(0, 200) : ''
|
||||
);
|
||||
|
||||
return config;
|
||||
});
|
||||
|
||||
request.interceptors.response.use(
|
||||
(response) => {
|
||||
console.log(
|
||||
`[API] ${response.status} ${response.config.url}`,
|
||||
Array.isArray(response.data) ? `(${response.data.length} items)` : ''
|
||||
);
|
||||
return response.data;
|
||||
},
|
||||
(error) => {
|
||||
const status = error.response?.status;
|
||||
const url = error.config?.url;
|
||||
const detail = error.response?.data?.detail;
|
||||
const msg = detail || error.message || '未知错误';
|
||||
|
||||
if (status === 401) {
|
||||
console.warn(`[API] 401 Unauthorized: ${url} — redirecting to login`);
|
||||
localStorage.removeItem('token');
|
||||
window.location.href = '/login';
|
||||
} else if (status === 500) {
|
||||
console.error(`[API] 500 Internal Error: ${url}`, detail || error.message);
|
||||
} else if (status === 429) {
|
||||
toast('warning', msg);
|
||||
} else if (status === 422) {
|
||||
console.warn(`[API] 422 Validation Error: ${url}`, error.response?.data);
|
||||
// 验证错误 — 取第一个错误信息
|
||||
const errors = error.response?.data?.detail;
|
||||
if (Array.isArray(errors)) {
|
||||
const first = errors[0];
|
||||
toast('error', first?.msg || '请求参数错误');
|
||||
} else {
|
||||
toast('error', typeof errors === 'string' ? errors : '请求参数错误');
|
||||
}
|
||||
} else if (status && status >= 400) {
|
||||
toast('error', msg);
|
||||
} else {
|
||||
console.warn(`[API] ${status || 'NETWORK'} Error: ${url}`, detail || error.message);
|
||||
toast('error', '网络连接失败');
|
||||
}
|
||||
|
||||
return Promise.reject(error);
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { X, CheckCircle2, AlertCircle, AlertTriangle, Info } from 'lucide-react';
|
||||
|
||||
const ICONS = {
|
||||
success: CheckCircle2,
|
||||
error: AlertCircle,
|
||||
warning: AlertTriangle,
|
||||
info: Info,
|
||||
};
|
||||
|
||||
const COLORS = {
|
||||
success: 'bg-green-500/10 border-green-500/30 text-green-400',
|
||||
error: 'bg-red-500/10 border-red-500/30 text-red-400',
|
||||
warning: 'bg-yellow-500/10 border-yellow-500/30 text-yellow-400',
|
||||
info: 'bg-blue-500/10 border-blue-500/30 text-blue-400',
|
||||
};
|
||||
|
||||
export function ToastContainer() {
|
||||
const { toasts, remove } = useToast();
|
||||
|
||||
if (toasts.length === 0) return null;
|
||||
|
||||
return (
|
||||
<div className="fixed top-4 right-4 z-[9999] flex flex-col gap-2 max-w-sm">
|
||||
{toasts.map(t => {
|
||||
const Icon = ICONS[t.type];
|
||||
return (
|
||||
<div
|
||||
key={t.id}
|
||||
className={`flex items-center gap-3 px-4 py-3 rounded-lg border backdrop-blur-sm animate-in slide-in-from-right fade-in duration-200 ${COLORS[t.type]}`}
|
||||
>
|
||||
<Icon className="w-4 h-4 shrink-0" />
|
||||
<span className="text-sm flex-1">{t.message}</span>
|
||||
<button onClick={() => remove(t.id)} className="shrink-0 opacity-50 hover:opacity-100">
|
||||
<X className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,40 +1,33 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { CheckCircle, XCircle, X } from 'lucide-react';
|
||||
import { useCallback, useState } from 'react';
|
||||
|
||||
export interface Toast {
|
||||
id: number;
|
||||
type: 'success' | 'error' | 'warning' | 'info';
|
||||
message: string;
|
||||
type: 'success' | 'error';
|
||||
}
|
||||
|
||||
let toastId = 0;
|
||||
let _addToast: ((t: Toast) => void) | null = null;
|
||||
|
||||
export function toast(type: Toast['type'], message: string) {
|
||||
if (_addToast) {
|
||||
_addToast({ id: ++toastId, type, message });
|
||||
}
|
||||
}
|
||||
|
||||
export function useToast() {
|
||||
const [toast, setToast] = useState<Toast | null>(null);
|
||||
const [toasts, setToasts] = useState<Toast[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!toast) return;
|
||||
const t = setTimeout(() => setToast(null), 3000);
|
||||
return () => clearTimeout(t);
|
||||
}, [toast]);
|
||||
|
||||
const showToast = useCallback((message: string, type: 'success' | 'error' = 'success') => {
|
||||
setToast({ message, type });
|
||||
_addToast = useCallback((t: Toast) => {
|
||||
setToasts(prev => [...prev, t]);
|
||||
setTimeout(() => {
|
||||
setToasts(prev => prev.filter(x => x.id !== t.id));
|
||||
}, 4000);
|
||||
}, []);
|
||||
|
||||
const ToastComponent = () => {
|
||||
if (!toast) return null;
|
||||
const isSuccess = toast.type === 'success';
|
||||
return (
|
||||
<div
|
||||
className={`fixed bottom-6 right-6 z-[100] flex items-center gap-2 rounded-lg px-4 py-3 text-sm shadow-lg
|
||||
animate-[fadeInUp_0.25s_ease-out] ${isSuccess ? 'bg-green-500/15 text-green-400' : 'bg-red-500/15 text-red-400'}`}
|
||||
>
|
||||
{isSuccess ? <CheckCircle className="h-4 w-4 shrink-0" /> : <XCircle className="h-4 w-4 shrink-0" />}
|
||||
<span>{toast.message}</span>
|
||||
<button onClick={() => setToast(null)} className="ml-1 hover:opacity-70">
|
||||
<X className="h-3 w-3" />
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
const remove = useCallback((id: number) => {
|
||||
setToasts(prev => prev.filter(x => x.id !== id));
|
||||
}, []);
|
||||
|
||||
return { toast, showToast, ToastComponent };
|
||||
return { toasts, remove };
|
||||
}
|
||||
@@ -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>
|
||||
|
||||
Reference in new issue
Block a user