From 1a4bf6f18577d1ba2c8b6ce56a9e12ee4694353e Mon Sep 17 00:00:00 2001 From: Nixevol Date: Wed, 30 Sep 2026 14:55:36 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E9=99=90=E5=88=B6=E7=AE=A1=E7=90=86?= =?UTF-8?q?=E6=8E=A5=E5=8F=A3=E8=AF=B7=E6=B1=82=E4=BD=93=E5=A4=A7=E5=B0=8F?= =?UTF-8?q?=E4=B8=8E=E8=AF=BB=E5=8F=96=E6=97=B6=E9=97=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/DEVIATIONS.md | 9 ++++++ internal/admin/endpoints_csv.go | 17 +++++++++-- internal/admin/h01_test.go | 53 +++++++++++++++++++++++++++++++++ internal/admin/handler.go | 36 +++++++++++++++++++++- internal/admin/login.go | 4 +-- internal/httpx/json.go | 20 +++++++++++-- internal/httpx/json_test.go | 39 ++++++++++++++++++++++++ 7 files changed, 170 insertions(+), 8 deletions(-) create mode 100644 internal/admin/h01_test.go create mode 100644 internal/httpx/json_test.go diff --git a/docs/DEVIATIONS.md b/docs/DEVIATIONS.md index 0bde805..b6a0f9e 100644 --- a/docs/DEVIATIONS.md +++ b/docs/DEVIATIONS.md @@ -890,6 +890,15 @@ - 备选:无。 - 影响:无。 +### 复审修复 H-01 + +- 日期:2026-09-30 +- 原条款:PRD §8 管理员登录防暴力;审查 #44。 +- 实际做法:`httpx.DecodeJSON` 内部 `MaxBytesReader` 1 MiB;`admin.Handler.ServeHTTP` 按路由限制(登录 8 KiB、导入 8 MiB、其余 1 MiB)并设读截止时间;超限 413 JSON `payload_too_large`。CSV 导入不再在 8 MiB 处静默截断。不在 listener 加全局 `ReadTimeout`。 +- 原因:公开登录接口与 JSON 解码原先不限大小。 +- 备选方案:登录 4 KiB(与注册一致);未采用,8 KiB 对口令字段更宽裕。 +- 影响:超大请求快速失败;合法批量 JSON(约 200 KiB)仍低于 1 MiB。 + ## 后台网页 W 1. **W1–W3 阶段使用内存假数据,不请求真实 `/api/admin`** diff --git a/internal/admin/endpoints_csv.go b/internal/admin/endpoints_csv.go index 11b3fa5..eff12ec 100644 --- a/internal/admin/endpoints_csv.go +++ b/internal/admin/endpoints_csv.go @@ -37,6 +37,11 @@ func (h *Handler) handleEndpointImport(w http.ResponseWriter, r *http.Request) { raw, err := readImportCSV(r) if err != nil { + if httpx.IsBodyTooLarge(err) { + h.audit(actorString(p), "endpoint_import", "", "payload_too_large", ip) + httpx.WriteError(w, http.StatusRequestEntityTooLarge, "payload_too_large", "请求体过大") + return + } h.audit(actorString(p), "endpoint_import", "", "bad_request", ip) httpx.WriteError(w, http.StatusBadRequest, "bad_request", err.Error()) return @@ -91,9 +96,12 @@ func readImportCSV(r *http.Request) ([]byte, error) { } name := part.FormName() if name == "file" || name == "" { - b, readErr := io.ReadAll(io.LimitReader(part, 8<<20)) + b, readErr := io.ReadAll(part) _ = part.Close() if readErr != nil { + if httpx.IsBodyTooLarge(readErr) { + return nil, readErr + } return nil, errBadRequest("读取文件失败") } return b, nil @@ -102,9 +110,12 @@ func readImportCSV(r *http.Request) ([]byte, error) { } return nil, errBadRequest("缺少 file 字段") default: - // text/csv 或未标明时按原始体 - b, readErr := io.ReadAll(io.LimitReader(r.Body, 8<<20)) + // text/csv 或未标明时按原始体;大小由 ServeHTTP 的 MaxBytesReader 限制。 + b, readErr := io.ReadAll(r.Body) if readErr != nil { + if httpx.IsBodyTooLarge(readErr) { + return nil, readErr + } return nil, errBadRequest("读取 CSV 失败") } return b, nil diff --git a/internal/admin/h01_test.go b/internal/admin/h01_test.go new file mode 100644 index 0000000..f1e11d4 --- /dev/null +++ b/internal/admin/h01_test.go @@ -0,0 +1,53 @@ +package admin_test + +import ( + "bytes" + "io" + "net/http" + "strings" + "testing" +) + +func TestLoginRejectsOversizeBody(t *testing.T) { + _, srv, client, _ := setup(t) + body := `{"username":"admin","password":"` + strings.Repeat("a", 1<<20) + `"}` + req, err := http.NewRequest(http.MethodPost, srv.URL+"/api/admin/login", strings.NewReader(body)) + if err != nil { + t.Fatal(err) + } + req.Header.Set("Content-Type", "application/json") + res, err := client.Do(req) + if err != nil { + t.Fatal(err) + } + env := decodeEnv(t, res) + if res.StatusCode != http.StatusRequestEntityTooLarge { + t.Fatalf("want 413 got %d env=%+v", res.StatusCode, env) + } + if env.Error == nil || env.Error.Code != "payload_too_large" { + t.Fatalf("want payload_too_large got %+v", env.Error) + } +} + +func TestImportRejectsOversizeCSV(t *testing.T) { + _, srv, client, _, _ := setupEndpoints(t) + payload := bytes.Repeat([]byte("x"), 8<<20+1) + req, err := http.NewRequest(http.MethodPost, srv.URL+"/api/admin/endpoints/import", bytes.NewReader(payload)) + if err != nil { + t.Fatal(err) + } + req.Header.Set("Content-Type", "text/csv") + req.Header.Set("X-Nixmsg-Request", "1") + res, err := client.Do(req) + if err != nil { + t.Fatal(err) + } + raw, _ := io.ReadAll(res.Body) + _ = res.Body.Close() + if res.StatusCode != http.StatusRequestEntityTooLarge { + t.Fatalf("want 413 got %d body=%s", res.StatusCode, raw) + } + if !strings.Contains(string(raw), "payload_too_large") { + t.Fatalf("want payload_too_large in body: %s", raw) + } +} diff --git a/internal/admin/handler.go b/internal/admin/handler.go index e44b0a8..6787226 100644 --- a/internal/admin/handler.go +++ b/internal/admin/handler.go @@ -1,6 +1,7 @@ package admin import ( + "errors" "log/slog" "net" "net/http" @@ -11,6 +12,7 @@ import ( "git.asio.asia/nixevol/NixMsg/internal/app/identity" "git.asio.asia/nixevol/NixMsg/internal/auth" "git.asio.asia/nixevol/NixMsg/internal/config" + "git.asio.asia/nixevol/NixMsg/internal/httpx" "git.asio.asia/nixevol/NixMsg/internal/store" ) @@ -23,6 +25,13 @@ const ( defaultSessionTTL = 12 * time.Hour minPasswordLen = 12 lastUsedMinGap = time.Minute + + maxLoginBodyBytes = 8 << 10 + maxJSONBodyBytes = 1 << 20 + maxImportBodyBytes = 8 << 20 + defaultReadFor = 15 * time.Second + loginReadFor = 10 * time.Second + importReadFor = 2 * time.Minute ) // Deps 是管理 Handler 的依赖。 @@ -129,11 +138,36 @@ func New(d Deps) *Handler { return h } -// ServeHTTP 实现 http.Handler。 +// ServeHTTP 实现 http.Handler。按路由限制请求体大小与读截止时间。 func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { + limit, readFor := requestBodyBudget(r) + if err := http.NewResponseController(w).SetReadDeadline(time.Now().Add(readFor)); err != nil && !errors.Is(err, http.ErrNotSupported) { + // 测试用 ResponseRecorder 或不支持截止时间的封装:忽略。 + } + if r.Body != nil { + r.Body = http.MaxBytesReader(w, r.Body, limit) + } h.mux.ServeHTTP(w, r) } +func requestBodyBudget(r *http.Request) (int64, time.Duration) { + if r.Method == http.MethodPost && r.URL.Path == "/api/admin/endpoints/import" { + return maxImportBodyBytes, importReadFor + } + if r.Method == http.MethodPost && r.URL.Path == "/api/admin/login" { + return maxLoginBodyBytes, loginReadFor + } + return maxJSONBodyBytes, defaultReadFor +} + +func writeDecodeError(w http.ResponseWriter, err error) { + if httpx.IsBodyTooLarge(err) { + httpx.WriteError(w, http.StatusRequestEntityTooLarge, "payload_too_large", "请求体过大") + return + } + httpx.WriteError(w, http.StatusBadRequest, "bad_request", "请求体无效") +} + func (h *Handler) routes() { // 公开 h.mux.HandleFunc("POST /api/admin/login", h.handleLogin) diff --git a/internal/admin/login.go b/internal/admin/login.go index 306184e..63897a0 100644 --- a/internal/admin/login.go +++ b/internal/admin/login.go @@ -35,7 +35,7 @@ func (h *Handler) handleLogin(w http.ResponseWriter, r *http.Request) { Password string `json:"password"` } if err := httpx.DecodeJSON(r, &req); err != nil { - httpx.WriteError(w, http.StatusBadRequest, "bad_request", "请求体无效") + writeDecodeError(w, err) return } if req.Username != adminUsername { @@ -117,7 +117,7 @@ func (h *Handler) handlePassword(w http.ResponseWriter, r *http.Request) { } if err := httpx.DecodeJSON(r, &req); err != nil { h.audit(actorString(p), "password_change", "", "bad_request", ip) - httpx.WriteError(w, http.StatusBadRequest, "bad_request", "请求体无效") + writeDecodeError(w, err) return } if len(req.NewPassword) < minPasswordLen { diff --git a/internal/httpx/json.go b/internal/httpx/json.go index ecfac96..93175df 100644 --- a/internal/httpx/json.go +++ b/internal/httpx/json.go @@ -8,6 +8,17 @@ import ( "net/http" ) +const maxJSONBodyBytes = 1 << 20 + +// IsBodyTooLarge 判断是否因请求体超过 MaxBytesReader 上限而失败。 +func IsBodyTooLarge(err error) bool { + if err == nil { + return false + } + var maxErr *http.MaxBytesError + return errors.As(err, &maxErr) +} + // ErrorBody 是失败响应里的 error 对象。 type ErrorBody struct { Code string `json:"code"` @@ -46,10 +57,15 @@ func WriteError(w http.ResponseWriter, status int, code, message string) { }) } -// DecodeJSON 解码请求 JSON 体;空体对 dst 保持零值。 +// DecodeJSON 解码请求 JSON 体;空体对 dst 保持零值。内部把请求体限制在 1 MiB。 func DecodeJSON(r *http.Request, dst any) error { defer func() { _ = r.Body.Close() }() - dec := json.NewDecoder(r.Body) + body := r.Body + if body == nil { + return nil + } + body = http.MaxBytesReader(nil, body, maxJSONBodyBytes) + dec := json.NewDecoder(body) dec.DisallowUnknownFields() if err := dec.Decode(dst); err != nil { if errors.Is(err, io.EOF) { diff --git a/internal/httpx/json_test.go b/internal/httpx/json_test.go new file mode 100644 index 0000000..9307cc4 --- /dev/null +++ b/internal/httpx/json_test.go @@ -0,0 +1,39 @@ +package httpx + +import ( + "bytes" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +func TestDecodeJSONRejectsOversizeBody(t *testing.T) { + t.Parallel() + payload := `{"password":"` + strings.Repeat("a", 2<<20) + `"}` + req := httptest.NewRequest(http.MethodPost, "/x", strings.NewReader(payload)) + var dst struct { + Password string `json:"password"` + } + err := DecodeJSON(req, &dst) + if err == nil { + t.Fatal("want error for 2 MiB JSON body") + } + if !IsBodyTooLarge(err) { + t.Fatalf("want IsBodyTooLarge, got %v", err) + } +} + +func TestDecodeJSONAcceptsSmallBody(t *testing.T) { + t.Parallel() + req := httptest.NewRequest(http.MethodPost, "/x", bytes.NewReader([]byte(`{"password":"ok"}`))) + var dst struct { + Password string `json:"password"` + } + if err := DecodeJSON(req, &dst); err != nil { + t.Fatal(err) + } + if dst.Password != "ok" { + t.Fatalf("password=%q", dst.Password) + } +}