Skip to content

server: rate-limit invalid keys and harden console responses - #604

Open
guyu233 wants to merge 2 commits into
caigee-cmd:mainfrom
guyu233:upstream/server-guardrails
Open

guyu233 wants to merge 2 commits into
caigee-cmd:mainfrom
guyu233:upstream/server-guardrails

Conversation

@guyu233

@guyu233 guyu233 commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Problem

The console and gateway currently answer every invalid key with a SQLite-backed lookup, send large JSON responses uncompressed, and silently drop request-log writes when the single SQLite writer falls behind. The rendered console also has no Content-Security-Policy.

Change

  • internal/server/authlimit.go: per-client in-memory limiter for invalid API keys. Ten failures in a minute block that client for a minute with 429 and Retry-After; a successful auth clears the counter, and requests that present no credentials do not consume the scan budget.
  • internal/server/compress.go: gzip JSON for console /api/* (except /api/events and /api/chat) and /v1/models. SSE, chat streams, HEAD, and gzip;q=0 clients are untouched.
  • internal/server/middleware.go: enforce a tested Content-Security-Policy plus baseline nosniff / frame / referrer / permissions headers on every response.
  • internal/logs/recorder.go: raise the request-log queue from 256 to 4096, wait 25ms before dropping, log drops at most once per 30s, drain accepted writes on close instead of closing the channel under an active enqueue.
  • /health exposes log_dropped and log_queue.

This branch is based on upstream/main; it does not change release identities, version numbers, or fork-specific defaults.

Validation

  • go test ./...
  • go vet ./...
  • python scripts/release-notes.py self-test
  • python scripts/release-notes.py validate
  • git diff --check
  • New coverage: auth failure limit / cooldown / reset / missing credentials, gzip round-trip / SSE skip / q=0 / no header commit on panic, queue grace and close drain, CSP and health counters.

All six CI jobs (go, windows-host, worker, frontend, container, secrets) are green on the current head. Ready for review.

@guyu233
guyu233 marked this pull request as ready for review November 27, 2026 05:53
- enforce a Content-Security-Policy and baseline security headers
- gzip console JSON and /v1/models while leaving SSE and chat streams alone
- rate-limit repeated invalid API keys per client and return 429 with Retry-After
- enlarge the request-log queue, bound the pre-drop wait, and expose drop counters in /health
@guyu233
guyu233 force-pushed the upstream/server-guardrails branch from 2582085 to 1f4f915 Compare November 27, 2026 05:54
@caigee-cmd

Copy link
Copy Markdown
Owner

看过了,可以合,等这轮 CI。

  • 限流只计校验失败的密钥:同一来源一分钟内十次失败后封一分钟并回 429 加 Retry-After,成功一次就清零;没带任何密钥的请求不计入,所以控制台登录页的刷新不会被算进去。计数在内存里,超上限就清空,重启即归零。
  • gzip 跳过了 /api/events、/api/chat、SSE、HEAD 和声明 gzip;q=0 的客户端。
  • CSP 允许 'self' 和样式的 'unsafe-inline',控制台现有的内联样式不受影响;frame-ancestors 'self' 配合 X-Frame-Options: SAMEORIGIN。
  • 请求日志队列从 256 提到 4096,丢弃前等 25 毫秒,丢弃日志最多 30 秒一条,/health 里能看到 log_dropped 和 log_queue。

没有动发布源、版本号或路由行为。CI 绿了我就合。

@caigee-cmd caigee-cmd left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Direction is right: CSP, skipping gzip on /api/events and /api/chat, raising the log queue from 256 to 4096, waiting 25ms, and draining accepted writes on close are all good. CI is green. Two things to fix before merge.

Auth limiter keys on the raw peer address. clientIP uses r.RemoteAddr and never reads X-Forwarded-For / X-Real-Ip. Behind the reverse proxy this repo is deployed with, every client is one IP. Ten bad keys in a minute — including ten different people, or one shared NAT — 429s the whole console for a minute, and a later successful key from anyone on that address clears the counter via success(). Either document that this only works when the process is reached directly, or key the bucket on the forwarded client (only from a trusted proxy hop) plus a short hash of the presented secret so one scanner cannot lock everyone else out.

withJSONCompression swallows http.Flusher until the first write. Flush commits with allowCompress=false, which is correct, but only if the handler type-asserts http.Flusher on the wrapper. jsonResponseWriter.Flush exists, so SSE that asserts against the wrapper is fine; an assertion against the inner writer fails and the 15s comment heartbeat in #603 would buffer. Worth a test that an /api/* handler which is not in the skip list can still flush, or keep the skip list explicit for every streaming route. /api/accounts/.../login is plain JSON today, so this is not a Hijacker break.

/health exposing log_dropped and log_queue is what we want. No change requested on the CSP itself.

@caigee-cmd

Copy link
Copy Markdown
Owner

需要改什么

CSP、gzip 跳过 /api/events 和 /api/chat、日志队列从 256 提到 4096、入队先等 25ms、关闭时排空,这些可以留。CI 是绿的。合之前要改两处行为,并补上对应测试。

1. 鉴权失败桶不能只用连接对端地址

internal/server/authlimit.go 的 clientIP:

addr := strings.TrimSpace(r.RemoteAddr)
if host, _, err := net.SplitHostPort(addr); err == nil {
    return host
}

桶的 key 就是这个字符串。failure 在 1 分钟内累计到 10 次(authFailureLimit)就把这个 key 封 1 分钟,withAPIKey 在 查 key 之前 就调用 blocked。

这个进程的部署方式是容器加反代(deploy/docker-compose.yml 的 qoder-api-proxy,前面通常是 Caddy/Nginx)。那时 RemoteAddr 永远是反代自己,例如 172.x.x.x:port。后果:

  • 任意客户端 10 次错误 key,整个控制台和全部 /v1/* 一起 429,Retry-After 60。
  • 同一个 NAT、同一个公司出口也会互相锁。
  • success() 在 该地址 上任何一次成功鉴权后执行 delete(l.entries, client)。反代后面一个人登录成功,会把正在扫 key 的那个人的计数清掉。限流对扫描没有用,对正常人有用,方向反了。

credentialsPresented 只认 Authorization: Bearer 和 x-api-key,空凭证不计数,这点是对的,请保持。

请改成下面这个桶,而不是“读一下 X-Forwarded-For 就拿最左边”:

  1. 默认仍然用 RemoteAddr。不要无条件信任 X-Forwarded-For。客户端可以自己写这个头,直接信任会让扫描者每请求换一个 IP,限流等于没有;伪造的内网 IP 还会去挤 authFailureMaxEntries。
  2. 只有当 RemoteAddr 落在显式配置的信任网段里时,才取转发头。加一个环境变量,例如 CLI2API_TRUSTED_PROXY_CIDR(逗号分隔的 CIDR)。没配置就保持今天的行为,并在 deploy/README.md 写明:反代部署不设这个变量时,限流是按反代 IP 而不是按用户。
  3. 取转发地址时用最接近信任网段的那一跳,不要用最左边。X-Forwarded-For: <client>, <edge> 里,边缘反代追加的是右边。只信任从 RemoteAddr 往左、且仍在信任网段内的连续跳,再往左的那一个才是客户端。
  4. 桶 key 不要只用 IP。用 ip + "\n" + sha256(presented secret)[:8]。没带凭证的请求本来就不计数。这样同一个出口后面,A 的错误 key 不会把 B 锁住,也不会在成功时被 B 清掉。success() 只删除自己这个 key 的条目。
  5. 哈希足够,不要把密钥原文放进 entries。这个 map 已经会在 4096 条时整表清空(pruneLocked),key 里再放原文没有必要。

测试要补的不是现有那组“10 次后 429、成功后清零”。现有测试用的是直接 RemoteAddr,覆盖不到反代。请加:

  • 不设信任网段时,X-Forwarded-For 被忽略,桶仍然是 RemoteAddr。
  • 设了信任网段且 RemoteAddr 在里面时,两个不同转发 IP 互不影响;同一个转发 IP 上两个不同错误 key 也互不影响。
  • RemoteAddr 不在信任网段时,即使带了转发头,也不采用。
  • 一次成功只清自己那把 key 的桶,不清同一 IP 下另一把错误 key。

2. gzip 包装器把 http.Flusher 藏起来了

internal/server/compress.go 的 withJSONCompression 对所有 /api/*(除了 /api/events、/api/chat)包了一层 jsonResponseWriter。

Flush() 在第一次调用时 commit(false),自己不压缩,这是对的。但只有断言到 包装器 的 Flush 才存在。标准库 http.NewResponseController 和很多 http.Flusher 断言会走包装器;不走 Unwrap() 的老写法会断言失败,然后把 SSE/分块响应一直缓冲到 handler 返回。

今天 /api/accounts/.../login 是普通 JSON(login/device、login/status、login/callback),没有 WebSocket upgrade,所以这不是 Hijacker 破坏。不要为了不存在的 upgrade 去实现 Hijack。

要修的是:所有会中途 flush 的 /api/* 都必须出现在 compressJSONPath 的排除列表里,或者包装器保证 http.NewResponseController(w).Flush() 在第一次 write 之前就成功且不打开 gzip。#603 的 /api/events 已经排除了。请再对一下 internal/server/router.go 里每个可能流式的 console 路由(现在是 /api/events、/api/chat;以后新增 SSE 必须进同一张表)。

补一个测试:对一个 没有 被排除的 /api/* 路径,handler 写入 Content-Type: application/json 后调用 Flush(),断言对端在 handler 返回之前就已经收到字节,并且响应没有 Content-Encoding: gzip。再对排除路径断言 Flush 不经过这层缓冲。现有 gzip 测试只覆盖了写完之后的压缩和 panic 时不提交,没有覆盖“写到一半就 flush”。

3. 日志队列这支可以不动

internal/logs/recorder.go 的改动是对的,合的时候保持:

  • 队列 4096,满了再等 requestLogQueueWait(25ms),超时记 dropped,日志每 30s 一条。
  • Close 先把 closed 设上,等 queueWG,再关 stop,loop 把已经进队列的 fn 排空。不要改回“对着正在 send 的 channel 执行 close”。
  • /health 的 log_dropped 和 log_queue 留着。

noteDrop 里 CompareAndSwap 失败就直接 return,极端情况下并发丢弃会少打一行日志,计数仍然是加过的。这个可以不改。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants