feat(security): add panel API rate limiting to protect DB from high-frequency requests

用户可高频刷面板接口(usage/dashboard 等重聚合查询)直接打爆数据库:
现有限流器只覆盖登录/注册等公开认证入口,登录后的全部面板端点无任何限流。

三层防护(阈值均可在后台可视化配置,panel_rate_limit_settings):

1. 认证面板接口按「用户 ID」限流,与来源 IP 无关——反向代理/NAT 共享出口
   (所有请求源地址坍缩为 127.0.0.1 等)不会互相误伤:
   - Global 档(默认 240 rpm/账号):user/auth/payment/admin 全部登录后路由
   - Heavy 档(默认 60 rpm/账号):/usage、/usage/dashboard/*、
     /user/api-keys/:id/usage/daily 等重 SQL 聚合端点叠加计数
   - 管理员默认豁免(可关闭)

2. 无认证公开接口(/api/v1/settings/*,每次请求都查 DB)按安全客户端 IP
   限流(默认 300 rpm/IP);回环/私网/链路本地地址(反代内部转发地址)
   一律跳过计数,杜绝把整条反代链路合并进同一个桶造成大面积误拦截。

3. 修复既有隐患:auth 入口限流的 IP 取值从 c.ClientIP() 切换到与审计日志/
   会话绑定/API Key ACL 同源的安全客户端 IP 解析(尊重后台「信任反代转发
   IP」开关快照)。原实现下默认反代部署(未配置 server.trusted_proxies)
   所有用户共享同一个登录限流桶,既会全员误拦也可被单人恶意占满形成登录
   DoS;开关关闭时行为与原来完全一致。

工程约束:
- 配置热路径走进程内缓存(atomic.Value + singleflight,60s TTL),
  限流中间件零 DB 访问;保存后当前节点立即生效
- 面板限流 Redis 故障 fail-open(auth 入口保持原有 fail-close)
- 429 响应携带 Retry-After;错误码 RATE_LIMITED
- 支付 webhook / 公开支付回调有意不挂限流
- 新增 GET/PUT /api/v1/admin/settings/panel-rate-limit;设置页安全 tab
  新增「面板接口限流」卡片(zh/en i18n 全量)

测试:rate_limiter/panel_rate_limit/setting_panel_rate_limit 单测全绿;
routes、handler/admin、-tags unit 契约测试通过;前端 vue-tsc/ESLint/
SettingsView spec(26/26,含新增交互用例)/i18n 守卫全部通过。
This commit is contained in:
shaw
2026-07-27 15:12:51 +08:00
parent d96b6a31ff
commit fead4c7ec3
23 changed files with 1460 additions and 26 deletions
+34
View File
@@ -1206,6 +1206,38 @@ export async function updateRateLimit429CooldownSettings(
return data;
}
// ==================== Panel Rate Limit Settings ====================
/**
* Panel API rate limit settings.
* Authenticated panel endpoints are limited per user account (reverse-proxy
* safe); public endpoints are limited per publicly routable client IP.
*/
export interface PanelRateLimitSettings {
enabled: boolean;
user_rpm: number;
heavy_rpm: number;
exempt_admin: boolean;
public_ip_rpm: number;
}
export async function getPanelRateLimitSettings(): Promise<PanelRateLimitSettings> {
const { data } = await apiClient.get<PanelRateLimitSettings>(
"/admin/settings/panel-rate-limit",
);
return data;
}
export async function updatePanelRateLimitSettings(
settings: PanelRateLimitSettings,
): Promise<PanelRateLimitSettings> {
const { data } = await apiClient.put<PanelRateLimitSettings>(
"/admin/settings/panel-rate-limit",
settings,
);
return data;
}
// ==================== Stream Timeout Settings ====================
/**
@@ -1433,6 +1465,8 @@ export const settingsAPI = {
updateOverloadCooldownSettings,
getRateLimit429CooldownSettings,
updateRateLimit429CooldownSettings,
getPanelRateLimitSettings,
updatePanelRateLimitSettings,
getStreamTimeoutSettings,
updateStreamTimeoutSettings,
getRectifierSettings,
@@ -135,6 +135,24 @@ export default {
auditRetention: 'Audit Log Retention (days)',
auditRetentionHint: 'Audit logs older than this are cleaned up automatically. Set to 0 to keep them forever (manual clear only).'
},
panelRateLimit: {
title: 'Panel API Rate Limiting',
description: 'Throttle panel API requests to keep high-frequency polling (usage stats, dashboard queries) from overwhelming the database',
proxySafeNote: 'Authenticated endpoints are counted per user account, independent of the source IP — reverse proxies and shared NAT egress are never falsely blocked. Public endpoints are counted per real client IP, and loopback/private addresses (internal proxy hops) are skipped automatically.',
enabled: 'Enable panel rate limiting',
enabledHint: 'Limits authenticated panel endpoints per account. Requests over the threshold get HTTP 429 and recover automatically when the window resets.',
userRpm: 'Requests per account',
userRpmHint: 'Total panel API requests allowed per account per minute. Normal UI usage stays far below this. 0 = unlimited.',
heavyRpm: 'Heavy queries per account',
heavyRpmHint: 'Usage/dashboard aggregation queries allowed per account per minute (these are the most expensive for the database). 0 = unlimited.',
publicIpRpm: 'Public endpoints per IP',
publicIpRpmHint: 'Requests per minute allowed per real client IP for unauthenticated endpoints (e.g. public site settings). 0 = unlimited.',
perMinute: 'req/min',
exemptAdmin: 'Exempt administrators',
exemptAdminHint: 'When enabled, admin accounts bypass panel rate limits so bulk operations are never throttled.',
saved: 'Panel rate limit settings saved',
saveFailed: 'Failed to save panel rate limit settings'
},
turnstile: {
title: 'Cloudflare Turnstile',
description: 'Bot protection for login and registration',
@@ -135,6 +135,24 @@ export default {
auditRetention: '操作日志保留天数',
auditRetentionHint: '超过该天数的操作日志将被自动清理;填 0 表示永久保留(仅支持手动清空)。'
},
panelRateLimit: {
title: '面板接口限流',
description: '限制面板 API 的请求频率,防止高频刷接口(如用量统计、仪表盘查询)打爆数据库',
proxySafeNote: '登录后的接口按「用户账号」维度计数,与来源 IP 无关——反向代理、NAT 共享出口等场景不会被误拦截;公开接口按真实客户端 IP 计数,回环与内网地址(反代内部转发地址)会自动跳过。',
enabled: '启用面板接口限流',
enabledHint: '对登录后的面板接口按账号限流;超出阈值返回 429,窗口重置后自动恢复。',
userRpm: '每账号请求上限',
userRpmHint: '单个账号每分钟允许的面板 API 请求总数,正常页面操作远达不到该阈值;0 表示不限制。',
heavyRpm: '重查询请求上限',
heavyRpmHint: '单个账号每分钟允许的用量/仪表盘等聚合统计查询次数(这类请求对数据库压力最大);0 表示不限制。',
publicIpRpm: '公开接口每 IP 上限',
publicIpRpmHint: '无需登录的公开接口(如站点公开设置)每个真实客户端 IP 每分钟的请求上限;0 表示不限制。',
perMinute: '次/分钟',
exemptAdmin: '管理员豁免',
exemptAdminHint: '开启后管理员账号不受面板限流约束,避免批量运维操作被误拦。',
saved: '面板接口限流配置已保存',
saveFailed: '保存面板接口限流配置失败'
},
turnstile: {
title: 'Cloudflare Turnstile',
description: '登录和注册的机器人防护',
+240
View File
@@ -1717,6 +1717,197 @@
</div>
</div>
<!-- Panel API Rate Limit Settings -->
<div class="card">
<div
class="border-b border-gray-100 px-6 py-4 dark:border-dark-700"
>
<div class="flex items-center gap-2">
<Icon
name="shield"
size="md"
class="text-primary-500"
/>
<h2 class="text-lg font-semibold text-gray-900 dark:text-white">
{{ t("admin.settings.panelRateLimit.title") }}
</h2>
</div>
<p class="mt-1 text-sm text-gray-500 dark:text-gray-400">
{{ t("admin.settings.panelRateLimit.description") }}
</p>
</div>
<div class="space-y-5 p-6">
<div
v-if="panelRateLimitLoading"
class="flex items-center gap-2 text-gray-500"
>
<div
class="h-4 w-4 animate-spin rounded-full border-b-2 border-primary-600"
></div>
{{ t("common.loading") }}
</div>
<template v-else>
<!-- 计数维度说明:按账号计数,反代部署无误伤 -->
<div
class="rounded-lg border border-sky-200 bg-sky-50 p-4 dark:border-sky-800 dark:bg-sky-900/20"
>
<div class="flex items-start">
<Icon
name="infoCircle"
size="md"
class="mt-0.5 flex-shrink-0 text-sky-500"
/>
<p class="ml-3 text-sm text-sky-700 dark:text-sky-300">
{{ t("admin.settings.panelRateLimit.proxySafeNote") }}
</p>
</div>
</div>
<div class="flex items-center justify-between">
<div>
<label class="font-medium text-gray-900 dark:text-white">{{
t("admin.settings.panelRateLimit.enabled")
}}</label>
<p class="text-sm text-gray-500 dark:text-gray-400">
{{ t("admin.settings.panelRateLimit.enabledHint") }}
</p>
</div>
<Toggle v-model="panelRateLimitForm.enabled" />
</div>
<div
v-if="panelRateLimitForm.enabled"
class="space-y-5 border-t border-gray-100 pt-4 dark:border-dark-700"
>
<div class="grid grid-cols-1 gap-6 sm:grid-cols-2">
<div>
<label
class="mb-2 block text-sm font-medium text-gray-700 dark:text-gray-300"
>
{{ t("admin.settings.panelRateLimit.userRpm") }}
</label>
<div class="flex items-center gap-2">
<input
v-model.number="panelRateLimitForm.user_rpm"
data-testid="panel-rate-limit-user-rpm"
type="number"
min="0"
max="100000"
class="input w-32"
/>
<span class="text-sm text-gray-500 dark:text-gray-400">
{{ t("admin.settings.panelRateLimit.perMinute") }}
</span>
</div>
<p class="mt-1.5 text-xs text-gray-500 dark:text-gray-400">
{{ t("admin.settings.panelRateLimit.userRpmHint") }}
</p>
</div>
<div>
<label
class="mb-2 block text-sm font-medium text-gray-700 dark:text-gray-300"
>
{{ t("admin.settings.panelRateLimit.heavyRpm") }}
</label>
<div class="flex items-center gap-2">
<input
v-model.number="panelRateLimitForm.heavy_rpm"
type="number"
min="0"
max="100000"
class="input w-32"
/>
<span class="text-sm text-gray-500 dark:text-gray-400">
{{ t("admin.settings.panelRateLimit.perMinute") }}
</span>
</div>
<p class="mt-1.5 text-xs text-gray-500 dark:text-gray-400">
{{ t("admin.settings.panelRateLimit.heavyRpmHint") }}
</p>
</div>
<div>
<label
class="mb-2 block text-sm font-medium text-gray-700 dark:text-gray-300"
>
{{ t("admin.settings.panelRateLimit.publicIpRpm") }}
</label>
<div class="flex items-center gap-2">
<input
v-model.number="panelRateLimitForm.public_ip_rpm"
type="number"
min="0"
max="100000"
class="input w-32"
/>
<span class="text-sm text-gray-500 dark:text-gray-400">
{{ t("admin.settings.panelRateLimit.perMinute") }}
</span>
</div>
<p class="mt-1.5 text-xs text-gray-500 dark:text-gray-400">
{{ t("admin.settings.panelRateLimit.publicIpRpmHint") }}
</p>
</div>
</div>
<div
class="flex items-center justify-between border-t border-gray-100 pt-4 dark:border-dark-700"
>
<div>
<label class="font-medium text-gray-900 dark:text-white">{{
t("admin.settings.panelRateLimit.exemptAdmin")
}}</label>
<p class="text-sm text-gray-500 dark:text-gray-400">
{{ t("admin.settings.panelRateLimit.exemptAdminHint") }}
</p>
</div>
<Toggle v-model="panelRateLimitForm.exempt_admin" />
</div>
</div>
<div
class="flex justify-end border-t border-gray-100 pt-4 dark:border-dark-700"
>
<button
type="button"
data-testid="panel-rate-limit-save"
@click="savePanelRateLimitSettings"
:disabled="panelRateLimitSaving"
class="btn btn-primary btn-sm"
>
<svg
v-if="panelRateLimitSaving"
class="mr-1 h-4 w-4 animate-spin"
fill="none"
viewBox="0 0 24 24"
>
<circle
class="opacity-25"
cx="12"
cy="12"
r="10"
stroke="currentColor"
stroke-width="4"
></circle>
<path
class="opacity-75"
fill="currentColor"
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
></path>
</svg>
{{
panelRateLimitSaving
? t("common.saving")
: t("common.save")
}}
</button>
</div>
</template>
</div>
</div>
<!-- Cloudflare Turnstile Settings -->
<div class="card">
<div
@@ -7973,6 +8164,17 @@ const rateLimit429CooldownForm = reactive({
cooldown_seconds: 5,
});
// Panel API Rate Limit 状态
const panelRateLimitLoading = ref(true);
const panelRateLimitSaving = ref(false);
const panelRateLimitForm = reactive({
enabled: true,
user_rpm: 240,
heavy_rpm: 60,
exempt_admin: true,
public_ip_rpm: 300,
});
// Stream Timeout 状态
const streamTimeoutLoading = ref(true);
const streamTimeoutSaving = ref(false);
@@ -10638,6 +10840,43 @@ async function saveOverloadCooldownSettings() {
}
}
// Panel API Rate Limit 方法
async function loadPanelRateLimitSettings() {
panelRateLimitLoading.value = true;
try {
const settings = await adminAPI.settings.getPanelRateLimitSettings();
Object.assign(panelRateLimitForm, settings);
} catch (_error: unknown) {
// Silent fail - settings will use defaults
} finally {
panelRateLimitLoading.value = false;
}
}
async function savePanelRateLimitSettings() {
panelRateLimitSaving.value = true;
try {
const updated = await adminAPI.settings.updatePanelRateLimitSettings({
enabled: panelRateLimitForm.enabled,
user_rpm: panelRateLimitForm.user_rpm,
heavy_rpm: panelRateLimitForm.heavy_rpm,
exempt_admin: panelRateLimitForm.exempt_admin,
public_ip_rpm: panelRateLimitForm.public_ip_rpm,
});
Object.assign(panelRateLimitForm, updated);
appStore.showSuccess(t("admin.settings.panelRateLimit.saved"));
} catch (error: unknown) {
appStore.showError(
extractApiErrorMessage(
error,
t("admin.settings.panelRateLimit.saveFailed"),
),
);
} finally {
panelRateLimitSaving.value = false;
}
}
// Rate Limit Cooldown (429) 方法
async function loadRateLimit429CooldownSettings() {
rateLimit429CooldownLoading.value = true;
@@ -11304,6 +11543,7 @@ onMounted(() => {
loadOllamaCloudUsageSettings();
loadOverloadCooldownSettings();
loadRateLimit429CooldownSettings();
loadPanelRateLimitSettings();
loadStreamTimeoutSettings();
loadRectifierSettings();
loadBetaPolicySettings();
@@ -13,6 +13,8 @@ const {
getOverloadCooldownSettings,
getRateLimit429CooldownSettings,
updateRateLimit429CooldownSettings,
getPanelRateLimitSettings,
updatePanelRateLimitSettings,
getStreamTimeoutSettings,
getRectifierSettings,
getBetaPolicySettings,
@@ -39,6 +41,14 @@ const {
getOverloadCooldownSettings: vi.fn(),
getRateLimit429CooldownSettings: vi.fn(),
updateRateLimit429CooldownSettings: vi.fn(),
getPanelRateLimitSettings: vi.fn().mockResolvedValue({
enabled: true,
user_rpm: 240,
heavy_rpm: 60,
exempt_admin: true,
public_ip_rpm: 300,
}),
updatePanelRateLimitSettings: vi.fn().mockImplementation(async (payload) => payload),
getStreamTimeoutSettings: vi.fn(),
getRectifierSettings: vi.fn(),
getBetaPolicySettings: vi.fn(),
@@ -78,6 +88,8 @@ vi.mock("@/api", () => ({
getOverloadCooldownSettings,
getRateLimit429CooldownSettings,
updateRateLimit429CooldownSettings,
getPanelRateLimitSettings,
updatePanelRateLimitSettings,
getStreamTimeoutSettings,
getRectifierSettings,
getBetaPolicySettings,
@@ -662,6 +674,44 @@ describe("admin SettingsView payment visible method controls", () => {
adminSettingsFetch.mockResolvedValue(undefined);
});
it("renders panel rate limit card and saves settings", async () => {
getPanelRateLimitSettings.mockClear();
updatePanelRateLimitSettings.mockClear();
getPanelRateLimitSettings.mockResolvedValue({
enabled: true,
user_rpm: 240,
heavy_rpm: 60,
exempt_admin: true,
public_ip_rpm: 300,
});
updatePanelRateLimitSettings.mockImplementation(async (payload) => payload);
const wrapper = mountView();
await flushPromises();
expect(getPanelRateLimitSettings).toHaveBeenCalled();
expect(wrapper.text()).toContain("admin.settings.panelRateLimit.title");
expect(wrapper.text()).toContain("admin.settings.panelRateLimit.proxySafeNote");
const userRpmInput = wrapper.find('[data-testid="panel-rate-limit-user-rpm"]');
expect(userRpmInput.exists()).toBe(true);
await userRpmInput.setValue("120");
const saveButton = wrapper.find('[data-testid="panel-rate-limit-save"]');
expect(saveButton.exists()).toBe(true);
await saveButton.trigger("click");
await flushPromises();
expect(updatePanelRateLimitSettings).toHaveBeenCalledWith({
enabled: true,
user_rpm: 120,
heavy_rpm: 60,
exempt_admin: true,
public_ip_rpm: 300,
});
expect(showSuccess).toHaveBeenCalled();
});
it("does not render legacy visible payment method controls", async () => {
const wrapper = mountView();