mirror of
https://github.com/margrop/wrong-notebook.git
synced 2026-12-05 23:19:38 +08:00
feat: 为 MCP 端点增加鉴权失败与请求频率限流
- 按客户端 IP 限制 MCP 请求每分钟 120 次;鉴权失败 15 分钟内 20 次后锁定,超限返回 HTTP 429、JSON-RPC 错误体与 Retry-After。 - 鉴权成功后清零该 IP 的失败计数;取不到客户端 IP 时跳过限流。 - 集成测试覆盖鉴权失败与超速请求的 429 及计数清零;同步中英文 MCP 文档。 Refs: https://github.com/margrop/wrong-notebook/issues/96
This commit is contained in:
@@ -33,6 +33,14 @@ MCP_USER_EMAIL=student@example.com
|
||||
|
||||
密钥比较使用定长比较。密钥错误或账号不存在/停用时返回 `401`。密钥会出现在请求头中,跨网络访问应使用 HTTPS,避免写入日志。
|
||||
|
||||
## 限流
|
||||
|
||||
按客户端 IP(依次读取 `cf-connecting-ip`、`x-real-ip`、`x-forwarded-for` 的第一个地址)在进程内限流,计数保存在内存,重启后清零:
|
||||
|
||||
- 同一 IP 每分钟最多 120 个请求;超出返回 HTTP `429`,JSON-RPC 错误码 `-32000`,`Retry-After` 响应头给出等待秒数。该上限留足外部 agent 轮询后台任务的余量。
|
||||
- 同一 IP 15 分钟内鉴权失败 20 次后锁定;锁定期间即使提交正确密钥也返回 `429`(错误码 `-32001`),直到窗口过期。鉴权成功后清零该 IP 的失败计数,偶发错误密钥不会累积到锁定。
|
||||
- 取不到客户端 IP(未经反向代理的直接连接)时不按 IP 限流,避免所有调用方共用同一个计数。
|
||||
|
||||
## 客户端配置
|
||||
|
||||
Claude Code:
|
||||
|
||||
@@ -33,6 +33,14 @@ Either request header works:
|
||||
|
||||
The key is compared in constant time. A wrong key or a missing/disabled account returns `401`. The key travels in request headers, so use HTTPS across networks and keep it out of logs.
|
||||
|
||||
## Rate limiting
|
||||
|
||||
Limits are kept in process memory per client IP (the first address in `cf-connecting-ip`, `x-real-ip` or `x-forwarded-for`) and reset on restart:
|
||||
|
||||
- At most 120 requests per minute per IP; beyond that the endpoint returns HTTP `429` with JSON-RPC error code `-32000` and a `Retry-After` header in seconds. The limit leaves room for an external agent polling background tasks.
|
||||
- After 20 failed authentication attempts from one IP within 15 minutes, that IP is locked; during the lock even a correct key returns `429` (code `-32001`) until the window expires. A successful authentication clears the failure count for that IP, so occasional wrong keys do not accumulate into a lock.
|
||||
- When no client IP can be read (a direct connection without a reverse proxy), IP limits are skipped so callers do not share one counter.
|
||||
|
||||
## Client setup
|
||||
|
||||
Claude Code:
|
||||
|
||||
@@ -54,6 +54,7 @@ import { POST as MCP_POST, GET as MCP_GET } from '@/app/api/mcp/route';
|
||||
import { createErrorResponse } from '@/lib/api-errors';
|
||||
import { resetBackgroundTasksForTest } from '@/lib/background-tasks';
|
||||
import { waitForImportTaskForTest } from '@/lib/import/import-tasks';
|
||||
import { mcpAuthFailureIpLimiter, mcpIpLimiter } from '@/lib/rate-limit';
|
||||
|
||||
let database: PrismaClient;
|
||||
let directory: string;
|
||||
@@ -221,6 +222,61 @@ describe('MCP 服务', () => {
|
||||
expect(response.status).toBe(503);
|
||||
});
|
||||
|
||||
it('同一 IP 连续鉴权失败 20 次后返回 429 与 Retry-After', async () => {
|
||||
const ip = '203.0.113.20';
|
||||
mcpAuthFailureIpLimiter.reset(ip);
|
||||
mcpIpLimiter.reset(ip);
|
||||
const body = { jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2025-06-18' } };
|
||||
for (let i = 0; i < 20; i++) {
|
||||
const response = await MCP_POST(mcpRequest(body, { 'x-real-ip': ip, 'Authorization': 'Bearer wrong-key' }));
|
||||
expect(response.status).toBe(401);
|
||||
}
|
||||
// 锁定后即使密钥正确也先按 IP 拒绝
|
||||
const limited = await MCP_POST(mcpRequest(body, { 'x-real-ip': ip }));
|
||||
expect(limited.status).toBe(429);
|
||||
expect(Number(limited.headers.get('Retry-After'))).toBeGreaterThan(0);
|
||||
const payload = await limited.json() as { error: { code: number; message: string } };
|
||||
expect(payload.error.code).toBe(-32001);
|
||||
expect(payload.error.message).toContain('authentication');
|
||||
mcpAuthFailureIpLimiter.reset(ip);
|
||||
mcpIpLimiter.reset(ip);
|
||||
});
|
||||
|
||||
it('同一 IP 每分钟超过 120 个请求返回 429 与 Retry-After', async () => {
|
||||
const ip = '203.0.113.21';
|
||||
mcpAuthFailureIpLimiter.reset(ip);
|
||||
mcpIpLimiter.reset(ip);
|
||||
for (let i = 0; i < 120; i++) mcpIpLimiter.hit(ip);
|
||||
const limited = await MCP_POST(mcpRequest(
|
||||
{ jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2025-06-18' } },
|
||||
{ 'x-real-ip': ip },
|
||||
));
|
||||
expect(limited.status).toBe(429);
|
||||
expect(Number(limited.headers.get('Retry-After'))).toBeGreaterThan(0);
|
||||
const payload = await limited.json() as { error: { code: number; message: string } };
|
||||
expect(payload.error.code).toBe(-32000);
|
||||
expect(payload.error.message).toContain('Too many MCP requests');
|
||||
mcpIpLimiter.reset(ip);
|
||||
});
|
||||
|
||||
it('鉴权成功后清零同一 IP 的失败计数,偶发错误密钥不累积', async () => {
|
||||
const ip = '203.0.113.22';
|
||||
mcpAuthFailureIpLimiter.reset(ip);
|
||||
mcpIpLimiter.reset(ip);
|
||||
const body = { jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2025-06-18' } };
|
||||
for (let i = 0; i < 19; i++) {
|
||||
await MCP_POST(mcpRequest(body, { 'x-real-ip': ip, 'Authorization': 'Bearer wrong-key' }));
|
||||
}
|
||||
const ok = await MCP_POST(mcpRequest(body, { 'x-real-ip': ip }));
|
||||
expect(ok.status).toBe(200);
|
||||
// 若未清零,这次失败会把计数推到 20 并锁定
|
||||
const lastFailure = await MCP_POST(mcpRequest(body, { 'x-real-ip': ip, 'Authorization': 'Bearer wrong-key' }));
|
||||
expect(lastFailure.status).toBe(401);
|
||||
expect(mcpAuthFailureIpLimiter.retryAfter(ip)).toBe(0);
|
||||
mcpAuthFailureIpLimiter.reset(ip);
|
||||
mcpIpLimiter.reset(ip);
|
||||
});
|
||||
|
||||
it('初始化返回服务信息,工具清单包含全部工具', async () => {
|
||||
const init = await MCP_POST(mcpRequest({
|
||||
jsonrpc: '2.0',
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { createLogger } from "@/lib/logger";
|
||||
import { getClientIp, mcpAuthFailureIpLimiter, mcpIpLimiter } from "@/lib/rate-limit";
|
||||
import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
|
||||
import { authenticateMcpRequest } from "@/lib/mcp/auth";
|
||||
import { createMcpServer } from "@/lib/mcp/server";
|
||||
@@ -11,18 +12,22 @@ export const runtime = "nodejs";
|
||||
/** MCP 请求体上限:容纳含 base64 原图的 add_question 调用 */
|
||||
const MAX_REQUEST_BODY_SIZE = 24 * 1024 * 1024;
|
||||
|
||||
/** JSON-RPC 错误响应(HTTP 层鉴权或配置错误) */
|
||||
function mcpHttpError(status: number, code: number, message: string): Response {
|
||||
/** JSON-RPC 错误响应(HTTP 层鉴权、限流或配置错误);限流时附带 Retry-After 秒数 */
|
||||
function mcpHttpError(status: number, code: number, message: string, retryAfterMs?: number): Response {
|
||||
const headers = new Headers({
|
||||
"Content-Type": "application/json",
|
||||
"Cache-Control": "no-store",
|
||||
});
|
||||
if (retryAfterMs !== undefined) {
|
||||
headers.set("Retry-After", String(Math.max(1, Math.ceil(retryAfterMs / 1000))));
|
||||
}
|
||||
return new Response(JSON.stringify({
|
||||
jsonrpc: "2.0",
|
||||
id: null,
|
||||
error: { code, message },
|
||||
}), {
|
||||
status,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Cache-Control": "no-store",
|
||||
},
|
||||
headers,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -46,10 +51,28 @@ function normalizeMcpAccept(req: Request): Request {
|
||||
* 每个请求创建独立传输与服务实例,不依赖 Mcp-Session-Id;POST 返回 JSON 响应。
|
||||
*/
|
||||
export async function POST(req: Request) {
|
||||
// 按客户端 IP 限流:取不到 IP(未经代理的直接连接)时跳过,避免所有调用方共用计数
|
||||
const clientIp = getClientIp(req.headers);
|
||||
if (clientIp) {
|
||||
const requestRetryAfter = mcpIpLimiter.retryAfter(clientIp);
|
||||
if (requestRetryAfter > 0) {
|
||||
return mcpHttpError(429, -32000, "Too many MCP requests; retry after the indicated delay", requestRetryAfter);
|
||||
}
|
||||
mcpIpLimiter.hit(clientIp);
|
||||
const authRetryAfter = mcpAuthFailureIpLimiter.retryAfter(clientIp);
|
||||
if (authRetryAfter > 0) {
|
||||
return mcpHttpError(429, -32001, "Too many failed MCP authentication attempts; retry after the indicated delay", authRetryAfter);
|
||||
}
|
||||
}
|
||||
|
||||
const auth = await authenticateMcpRequest(req);
|
||||
if (!auth.ok) {
|
||||
// 只把 401 计为鉴权失败;未配置服务(503)不是调用方的错误
|
||||
if (clientIp && auth.status === 401) mcpAuthFailureIpLimiter.hit(clientIp);
|
||||
return mcpHttpError(auth.status, -32001, auth.message);
|
||||
}
|
||||
// 鉴权成功后清零该 IP 的失败计数,偶发错误密钥不会累积到锁定
|
||||
if (clientIp) mcpAuthFailureIpLimiter.reset(clientIp);
|
||||
|
||||
const transport = new WebStandardStreamableHTTPServerTransport({
|
||||
sessionIdGenerator: undefined,
|
||||
|
||||
@@ -113,3 +113,7 @@ export const registerIpLimiter = new RateLimiter({ limit: 10, windowMs: 60 * 60
|
||||
export const telemetryIpLimiter = new RateLimiter({ limit: 60, windowMs: 60 * 1000 });
|
||||
/** Openclaw 批量上传:同一来源 IP 每分钟最多 30 个请求 */
|
||||
export const openclawIpLimiter = new RateLimiter({ limit: 30, windowMs: 60 * 1000 });
|
||||
/** MCP 请求:同一来源 IP 每分钟最多 120 个,留足外部 agent 正常轮询后台任务的余量 */
|
||||
export const mcpIpLimiter = new RateLimiter({ limit: 120, windowMs: 60 * 1000 });
|
||||
/** MCP 鉴权失败:同一来源 IP 15 分钟内错 20 次即锁定,防止暴力尝试集成密钥 */
|
||||
export const mcpAuthFailureIpLimiter = new RateLimiter({ limit: 20, windowMs: FIFTEEN_MINUTES });
|
||||
|
||||
Reference in New Issue
Block a user