security: 补上认证面与输入边界的四处防护

链路功能已经跑通,缺的是边界。这几处默认值都是仓库里公开已知的,忘配就等于没有认证。

- 认证端点限速:/auth/login、/auth/register 此前完全没接限速器(Limiter 只挂在代理
  Auth 上),爆破与批量建号零成本。新增 AllowWindow 滑动窗口,登录按「单 IP」和
  「单 IP×账号」两个桶(默认 30/min、10/min),注册按 IP(5/min)且在 argon2 之前拦,
  避免光靠建号请求打满 CPU;超限返回 429 + Retry-After。
- 生产启动断言:env=production 时拒绝默认 OT_JWT_SECRET、缺失或短于 16 字节的
  OT_MASTER_KEY(缺失时 NewEncryptor 会用 sha256("") 派生,渠道密文可被公开还原)、
  默认管理员密码;一次列全所有问题,不再改一个试一个。development 不拦。
- 请求体上限:parseBody 原来全量 io.ReadAll 且全项目没有一处 MaxBytesReader,
  合法密钥可把任意大 body 整份压进内存再转发。/v1 组挂 BodyLimit(默认 32MB,
  OT_PROXY_MAX_BODY_MB),超限按客户端协议返回 413 request_too_large 并点名上限。
- CORS:不再无条件反射 Origin + Allow-Credentials: true——那唯一挡住跨站凭据读取的
  是 refresh cookie 的 SameSite=Lax,改成 None 就立刻变成窃取面。改为显式白名单,
  空白名单完全不发跨域头(同源部署与 vite proxy 本来就不需要),通配 * 不配凭据;
  允许头补上 X-Api-Key / Anthropic-Version / OpenAI-*,否则浏览器里跑官方 SDK 预检会挂。
- 配套 OT_SERVER_TRUSTED_PROXIES:不配置就不信 X-Forwarded-For(防伪造头绕过 IP 限速)。

顺手删掉 .env.example 末尾重复的 OT_PROXY_LOG_RAW 段。
This commit is contained in:
Sakurasan committed 2026-10-17 03:25:30 +08:00
1 parent d4c5263f1e
commit ad10bdc400
14 files changed
+521 -28

No files matched your search

+3 -1
View File
@@ -41,6 +41,7 @@ type Gateway struct {
// 上游超时兜底值(渠道 timeout_ms 非法时使用);按超时值缓存 Transport 复用连接池。
gwTimeout time.Duration
maxBodyMB int // /v1 请求体上限(MB),仅用于超限报错文案
tpMu sync.Mutex
tps map[time.Duration]*http.Transport
@@ -131,7 +132,7 @@ func contains(list []string, s string) bool {
return false
}
func NewGateway(db *gorm.DB, enc *crypto.Encryptor, rec *usage.Recorder, lim *ratelimit.Limiter, userRPS int, logRaw bool, gw_timeout time.Duration) *Gateway {
func NewGateway(db *gorm.DB, enc *crypto.Encryptor, rec *usage.Recorder, lim *ratelimit.Limiter, userRPS int, logRaw bool, gw_timeout time.Duration, maxBodyMB int) *Gateway {
return &Gateway{
db: db,
ch: channel.NewService(db, enc),
@@ -141,6 +142,7 @@ func NewGateway(db *gorm.DB, enc *crypto.Encryptor, rec *usage.Recorder, lim *ra
userRPS: userRPS,
logRaw: logRaw,
gwTimeout: gw_timeout,
maxBodyMB: maxBodyMB,
tps: map[time.Duration]*http.Transport{},
}
}
+16 -3
View File
@@ -1,6 +1,8 @@
package proxy
import (
"errors"
"fmt"
"net/http"
"github.com/gin-gonic/gin"
@@ -8,6 +10,17 @@ import (
"github.com/openteam/server/internal/store"
)
// failBodyRead 读取请求体失败时的报错:超限单独回 413,让客户端能区分"体太大"和"体畸形"。
func (g *Gateway) failBodyRead(c *gin.Context, err error) {
var mb *http.MaxBytesError
if errors.As(err, &mb) {
apiError(c, http.StatusRequestEntityTooLarge, "request_too_large",
fmt.Sprintf("请求体超过网关上限 %d MB", g.maxBodyMB))
return
}
apiError(c, http.StatusBadRequest, "invalid_request_error", "failed to read request body")
}
// chatCompletions POST /v1/chat/completions
func (g *Gateway) chatCompletions(c *gin.Context) {
u, ok := g.resolveUser(c)
@@ -19,7 +32,7 @@ func (g *Gateway) chatCompletions(c *gin.Context) {
}
br, body, err := parseBody(c)
if err != nil {
apiError(c, http.StatusBadRequest, "invalid_request_error", "failed to read request body")
g.failBodyRead(c, err)
return
}
c.Set("protocol", convert.ProtoChat)
@@ -52,7 +65,7 @@ func (g *Gateway) responses(c *gin.Context) {
}
br, body, err := parseBody(c)
if err != nil {
apiError(c, http.StatusBadRequest, "invalid_request_error", "failed to read request body")
g.failBodyRead(c, err)
return
}
c.Set("protocol", convert.ProtoResponses)
@@ -85,7 +98,7 @@ func (g *Gateway) messages(c *gin.Context) {
}
br, body, err := parseBody(c)
if err != nil {
apiError(c, http.StatusBadRequest, "invalid_request_error", "failed to read request body")
g.failBodyRead(c, err)
return
}
c.Set("protocol", convert.ProtoMessages)
+30 -2
View File
@@ -76,7 +76,7 @@ func newHarness(t *testing.T, baseURL string, timeoutMS int, bind bool, keyModel
rec := usage.NewRecorder(db)
t.Cleanup(rec.Close)
return &harness{
gw: NewGateway(db, enc, rec, ratelimit.New(), 0, false, 300*time.Second),
gw: NewGateway(db, enc, rec, ratelimit.New(), 0, false, 300*time.Second, 32),
db: db, rec: rec, key: plain,
}
}
@@ -294,7 +294,7 @@ func TestRuntimeFailureCounterResetsOnSuccess(t *testing.T) {
// 回归:全局兜底超时值不再被二次换算。
func TestGatewayTimeoutIsNotMultiplied(t *testing.T) {
gw := NewGateway(nil, nil, nil, nil, 0, false, 30*time.Second)
gw := NewGateway(nil, nil, nil, nil, 0, false, 30*time.Second, 8)
if got := gw.channelTimeout(&store.Channel{TimeoutMS: 0}); got != 30*time.Second {
t.Fatalf("兜底超时 = %s,期望 30s", got)
}
@@ -305,3 +305,31 @@ func TestGatewayTimeoutIsNotMultiplied(t *testing.T) {
t.Fatalf("client.Timeout 应为 0(由 context 控制整段时长),实际 %s", c.Timeout)
}
}
// 请求体超过上限时应按客户端协议返回 413(上限由 /v1 组的 BodyLimit 中间件把住)。
func TestRequestBodyTooLarge(t *testing.T) {
h := newHarness(t, "http://127.0.0.1:1", 0, true, nil)
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
req := httptest.NewRequest(http.MethodPost, "/v1/chat/completions",
strings.NewReader(`{"model":"m1","messages":[{"role":"user","content":"`+strings.Repeat("x", 4096)+`"}]}`))
req.Header.Set("Authorization", "Bearer "+h.key)
// 模拟 middleware.BodyLimit:超限后 ReadAll 拿到 *http.MaxBytesError
req.Body = http.MaxBytesReader(w, req.Body, 64)
c.Request = req
h.gw.Auth(c)
if !c.IsAborted() {
h.gw.Handle(c)
}
if w.Code != http.StatusRequestEntityTooLarge {
t.Fatalf("应返回 413,实际 %d: %s", w.Code, w.Body.String())
}
if !strings.Contains(w.Body.String(), "request_too_large") {
t.Fatalf("错误码不符:%s", w.Body.String())
}
if !strings.Contains(w.Body.String(), "32 MB") {
t.Fatalf("报错应点名上限,实际:%s", w.Body.String())
}
}