fix: 限制管理接口请求体大小与读取时间
This commit is contained in:
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user