[新增] 添加自动 IP 组规则测试功能,支持在保存前验证 Expr 规则命中情况

This commit is contained in:
ryan
2026-06-01 09:50:43 +08:00
parent 73beedfc09
commit b827baf19f
11 changed files with 287 additions and 26 deletions
@@ -4,6 +4,8 @@ import type {
WAFRuleGroup,
WAFRuleGroupPayload,
WAFIPGroup,
WAFIPGroupAutoTestPayload,
WAFIPGroupAutoTestResult,
WAFIPGroupPayload,
WAFIPGroupSyncResult,
WAFSiteRuleGroups,
@@ -84,3 +86,10 @@ export function syncWAFIPGroup(id: number) {
method: 'POST',
});
}
export function testWAFIPGroupAutoConfig(payload: WAFIPGroupAutoTestPayload) {
return apiRequest<WAFIPGroupAutoTestResult>('/waf/ip-groups/test', {
method: 'POST',
body: JSON.stringify(payload),
});
}
@@ -1,7 +1,7 @@
'use client';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { ArrowLeft, Download, Plus, Save, Trash2 } from 'lucide-react';
import { ArrowLeft, Download, Play, Plus, Save, Trash2 } from 'lucide-react';
import { useRouter } from 'next/navigation';
import { useEffect, useMemo, useState } from 'react';
@@ -16,10 +16,12 @@ import {
deleteWAFIPGroup,
getWAFIPGroups,
syncWAFIPGroup,
testWAFIPGroupAutoConfig,
updateWAFIPGroup,
} from '@/features/waf/api/waf';
import type {
WAFIPGroup,
WAFIPGroupAutoTestResult,
WAFIPGroupPayload,
WAFIPGroupSubscriptionFormat,
WAFIPGroupType,
@@ -101,14 +103,10 @@ function buildDraft(group: WAFIPGroup | null): IPGroupDraft {
}
function buildPayload(draft: IPGroupDraft): WAFIPGroupPayload {
let autoConfig: Record<string, unknown> = {};
if (draft.type === 'automatic') {
const parsed = JSON.parse(draft.auto_config_text || '{}') as unknown;
if (!parsed || Array.isArray(parsed) || typeof parsed !== 'object') {
throw new Error('自动配置必须是 JSON 对象。');
}
autoConfig = parsed as Record<string, unknown>;
}
const autoConfig =
draft.type === 'automatic'
? parseAutomaticConfig(draft.auto_config_text)
: {};
return {
name: draft.name,
type: draft.type,
@@ -123,6 +121,14 @@ function buildPayload(draft: IPGroupDraft): WAFIPGroupPayload {
};
}
function parseAutomaticConfig(text: string): Record<string, unknown> {
const parsed = JSON.parse(text || '{}') as unknown;
if (!parsed || Array.isArray(parsed) || typeof parsed !== 'object') {
throw new Error('自动配置必须是 JSON 对象。');
}
return parsed as Record<string, unknown>;
}
function appendAutomaticPresetRule(
autoConfigText: string,
rule: (typeof automaticPresetRules)[number],
@@ -161,6 +167,8 @@ export function WAFIPGroupsPage() {
const [selectedID, setSelectedID] = useState<number | null>(null);
const [draft, setDraft] = useState<IPGroupDraft>(emptyIPGroupDraft);
const [feedback, setFeedback] = useState<FeedbackState | null>(null);
const [autoTestResult, setAutoTestResult] =
useState<WAFIPGroupAutoTestResult | null>(null);
const groupsQuery = useQuery({
queryKey: ['waf', 'ip-groups'],
@@ -234,6 +242,28 @@ export function WAFIPGroupsPage() {
},
});
const testMutation = useMutation({
mutationFn: testWAFIPGroupAutoConfig,
onSuccess: (result) => {
setAutoTestResult(result);
setFeedback({
tone: result.matched_count > 0 ? 'success' : 'info',
message:
result.matched_count > 0
? `规则测试完成,命中 ${result.matched_count} 个 IP。`
: '规则测试完成,当前未命中任何 IP。',
});
},
onError: (error) => {
setAutoTestResult(null);
setFeedback({ tone: 'danger', message: getErrorMessage(error) });
},
});
useEffect(() => {
setAutoTestResult(null);
}, [draft.type, draft.auto_config_text, selectedID]);
if (groupsQuery.isLoading) {
return <LoadingState />;
}
@@ -254,6 +284,17 @@ export function WAFIPGroupsPage() {
}
};
const testDraft = () => {
try {
testMutation.mutate({
auto_config: parseAutomaticConfig(draft.auto_config_text),
});
} catch (error) {
setAutoTestResult(null);
setFeedback({ tone: 'danger', message: getErrorMessage(error) });
}
};
return (
<div className="space-y-6">
<PageHeader
@@ -328,6 +369,16 @@ export function WAFIPGroupsPage() {
}
action={
<div className="flex flex-wrap gap-3">
{draft.type === 'automatic' ? (
<SecondaryButton
type="button"
disabled={testMutation.isPending}
onClick={testDraft}
>
<Play className="mr-2 h-4 w-4" />
{testMutation.isPending ? '测试中...' : '测试规则'}
</SecondaryButton>
) : null}
{selectedGroup?.type === 'subscription' ||
selectedGroup?.type === 'automatic' ? (
<SecondaryButton
@@ -516,6 +567,39 @@ export function WAFIPGroupsPage() {
}
/>
</ResourceField>
{autoTestResult ? (
<div className="space-y-3 rounded-2xl border border-[var(--border-default)] bg-[var(--surface-muted)] p-4">
<div className="flex flex-wrap items-center justify-between gap-2">
<div className="text-sm font-semibold text-[var(--foreground-primary)]">
测试结果
</div>
<div className="text-xs text-[var(--foreground-secondary)]">
回看 {autoTestResult.lookback_minutes} 分钟 · 规则{' '}
{autoTestResult.rule_count} 条
</div>
</div>
<InlineMessage
tone={
autoTestResult.matched_count > 0 ? 'success' : 'info'
}
message={
autoTestResult.matched_count > 0
? `命中 ${autoTestResult.matched_count} 个 IP。`
: '当前没有匹配到任何 IP。'
}
/>
{autoTestResult.matched_count > 0 ? (
<div className="rounded-2xl border border-[var(--border-default)] bg-[var(--surface-elevated)] p-3">
<div className="mb-2 text-xs font-medium text-[var(--foreground-secondary)]">
命中 IP 列表
</div>
<pre className="overflow-x-auto whitespace-pre-wrap break-all text-sm text-[var(--foreground-primary)]">
{autoTestResult.matched_ips.join('\n')}
</pre>
</div>
) : null}
</div>
) : null}
</div>
) : (
<ResourceField
@@ -95,3 +95,15 @@ export interface WAFIPGroupSyncResult {
status: string;
message: string;
}
export interface WAFIPGroupAutoTestPayload {
auto_config: Record<string, unknown>;
}
export interface WAFIPGroupAutoTestResult {
matched_ips: string[];
matched_count: number;
lookback_minutes: number;
rule_count: number;
tested_at: string;
}
@@ -204,6 +204,69 @@ describe('WAF IP groups', () => {
expect(value).toContain('ip_host_count > 50 && ip_host_ratio > 0.5');
});
it('tests automatic Expr rules before saving', async () => {
const testMock = vi.fn();
vi.stubGlobal(
'fetch',
vi.fn((input: RequestInfo | URL, init?: RequestInit) => {
const url = String(input);
const method = init?.method?.toUpperCase() ?? 'GET';
if (url.includes('/waf/ip-groups/test') && method === 'POST') {
testMock(JSON.parse(String(init?.body)));
return Promise.resolve(
new Response(
JSON.stringify({
success: true,
message: '',
data: {
matched_ips: ['203.0.113.10', '203.0.113.11'],
matched_count: 2,
lookback_minutes: 60,
rule_count: 1,
tested_at: '2026-06-01T00:00:00Z',
},
}),
),
);
}
if (url.includes('/waf/ip-groups')) {
return Promise.resolve(
new Response(
JSON.stringify({ success: true, message: '', data: [] }),
),
);
}
return Promise.reject(new Error(`Unhandled fetch: ${url}`));
}),
);
renderWithProviders(<WAFIPGroupsPage />);
await screen.findByText('暂无 IP 组');
await userEvent.click(screen.getByRole('button', { name: /新建 IP 组/ }));
await userEvent.selectOptions(screen.getByLabelText('类型'), 'automatic');
await userEvent.click(screen.getByText('单 IP 404 高频扫描'));
await userEvent.click(screen.getByRole('button', { name: /测试规则/ }));
expect(await screen.findByText('命中 2 个 IP。')).toBeInTheDocument();
expect(screen.getByText('203.0.113.10')).toBeInTheDocument();
expect(screen.getByText('203.0.113.11')).toBeInTheDocument();
expect(testMock).toHaveBeenCalledWith({
auto_config: expect.objectContaining({
lookback_minutes: 60,
rules: [
expect.objectContaining({
expr: 'request_count > 100 && status_404_ratio >= 0.8',
}),
],
}),
});
});
it('opens IP group management from WAF page and references an IP group', async () => {
vi.stubGlobal(
'fetch',