链路功能已经跑通,缺的是边界。这几处默认值都是仓库里公开已知的,忘配就等于没有认证。
- 认证端点限速:/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 段。
171 lines
4.7 KiB
Go
171 lines
4.7 KiB
Go
package proxy
|
||
|
||
import (
|
||
"errors"
|
||
"fmt"
|
||
"net/http"
|
||
|
||
"github.com/gin-gonic/gin"
|
||
"github.com/openteam/server/internal/proxy/convert"
|
||
"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)
|
||
if !ok {
|
||
return
|
||
}
|
||
if !g.checkBalance(c, u) {
|
||
return
|
||
}
|
||
br, body, err := parseBody(c)
|
||
if err != nil {
|
||
g.failBodyRead(c, err)
|
||
return
|
||
}
|
||
c.Set("protocol", convert.ProtoChat)
|
||
c.Set("model_name", br.Model)
|
||
g.recordRawRequest(c, u, body)
|
||
if !g.checkModelAllowed(c, u, br.Model) {
|
||
apiError(c, http.StatusForbidden, "model_not_allowed", "模型未对你开放,请联系管理员")
|
||
return
|
||
}
|
||
|
||
cands := g.candidateChannels(br.Model)
|
||
if len(cands) == 0 {
|
||
apiError(c, http.StatusServiceUnavailable, "no_channel", "No available upstream channel")
|
||
g.recordError(c, nil, nil, now(), "no_channel")
|
||
return
|
||
}
|
||
sink := &usageSink{}
|
||
c.Set("usage_raw", &sinkHolder{sink: sink})
|
||
g.doProxy(c, cands, convert.ProtoChat, body, br.Stream, sink)
|
||
}
|
||
|
||
// responses POST /v1/responses(OpenAI Responses API)
|
||
func (g *Gateway) responses(c *gin.Context) {
|
||
u, ok := g.resolveUser(c)
|
||
if !ok {
|
||
return
|
||
}
|
||
if !g.checkBalance(c, u) {
|
||
return
|
||
}
|
||
br, body, err := parseBody(c)
|
||
if err != nil {
|
||
g.failBodyRead(c, err)
|
||
return
|
||
}
|
||
c.Set("protocol", convert.ProtoResponses)
|
||
c.Set("model_name", br.Model)
|
||
g.recordRawRequest(c, u, body)
|
||
if !g.checkModelAllowed(c, u, br.Model) {
|
||
apiError(c, http.StatusForbidden, "model_not_allowed", "模型未对你开放,请联系管理员")
|
||
return
|
||
}
|
||
|
||
cands := g.candidateChannels(br.Model)
|
||
if len(cands) == 0 {
|
||
apiError(c, http.StatusServiceUnavailable, "no_channel", "No available upstream channel")
|
||
g.recordError(c, nil, nil, now(), "no_channel")
|
||
return
|
||
}
|
||
sink := &usageSink{}
|
||
c.Set("usage_raw", &sinkHolder{sink: sink})
|
||
g.doProxy(c, cands, convert.ProtoResponses, body, br.Stream, sink)
|
||
}
|
||
|
||
// messages POST /v1/messages(Anthropic Messages API)
|
||
func (g *Gateway) messages(c *gin.Context) {
|
||
u, ok := g.resolveUser(c)
|
||
if !ok {
|
||
return
|
||
}
|
||
if !g.checkBalance(c, u) {
|
||
return
|
||
}
|
||
br, body, err := parseBody(c)
|
||
if err != nil {
|
||
g.failBodyRead(c, err)
|
||
return
|
||
}
|
||
c.Set("protocol", convert.ProtoMessages)
|
||
c.Set("model_name", br.Model)
|
||
g.recordRawRequest(c, u, body)
|
||
if !g.checkModelAllowed(c, u, br.Model) {
|
||
apiError(c, http.StatusForbidden, "model_not_allowed", "模型未对你开放,请联系管理员")
|
||
return
|
||
}
|
||
|
||
cands := g.candidateChannels(br.Model)
|
||
if len(cands) == 0 {
|
||
apiError(c, http.StatusServiceUnavailable, "no_channel", "No available upstream channel")
|
||
g.recordError(c, nil, nil, now(), "no_channel")
|
||
return
|
||
}
|
||
sink := &usageSink{}
|
||
c.Set("usage_raw", &sinkHolder{sink: sink})
|
||
g.doProxy(c, cands, convert.ProtoMessages, body, br.Stream, sink)
|
||
}
|
||
|
||
// usageSinkHolder 桥接:gin context 里保存 sink 引用,供 finishUsage 读取最终 usage。
|
||
type sinkHolder struct {
|
||
sink *usageSink
|
||
}
|
||
|
||
// recordRawRequest 记录管理员原始请求体到 context(供 finishUsage 落库)。
|
||
// 仅当开关开启且用户为管理员时记录;响应侧以 c.Get("raw_request") 是否非空判断是否需要捕获响应。
|
||
func (g *Gateway) recordRawRequest(c *gin.Context, u *store.User, body []byte) {
|
||
if g.logRaw && u.Role == store.RoleAdmin {
|
||
c.Set("raw_request", string(body))
|
||
}
|
||
}
|
||
|
||
// apiError 按客户端协议返回错误体(PLANNING §5.1.4)。
|
||
func apiError(c *gin.Context, status int, code, message string) {
|
||
if p, _ := c.Get("protocol"); p == convert.ProtoMessages {
|
||
// Anthropic 格式
|
||
c.AbortWithStatusJSON(status, gin.H{
|
||
"type": "error",
|
||
"error": gin.H{"type": errorTypeFor(status), "message": message},
|
||
})
|
||
return
|
||
}
|
||
// OpenAI 格式
|
||
c.AbortWithStatusJSON(status, gin.H{
|
||
"error": gin.H{
|
||
"message": message,
|
||
"type": errorTypeFor(status),
|
||
"param": nil,
|
||
"code": code,
|
||
},
|
||
})
|
||
}
|
||
|
||
func errorTypeFor(status int) string {
|
||
switch status {
|
||
case http.StatusUnauthorized:
|
||
return "authentication_error"
|
||
case http.StatusForbidden, http.StatusPaymentRequired:
|
||
return "permission_error"
|
||
case http.StatusNotFound, http.StatusBadRequest:
|
||
return "invalid_request_error"
|
||
case http.StatusTooManyRequests:
|
||
return "rate_limit_error"
|
||
default:
|
||
return "api_error"
|
||
}
|
||
}
|