Verify / verify (push) Canceled after 0s
增加安全字段校验提示、请求预算和就绪/存活探针, 让绑定、数据库、Redis 和出站响应解码保留可信诊断上下文。 补充完整应用装配及逆序清理示例,同步接入和迁移文档。 验证:make verify、make race-check 全部通过。 BREAKING CHANGE: 普通 Controller 默认启用 30 秒协作式请求预算, 可用 request_timeout_ms: 0 或 max-exec-time:"0" 关闭; 字段校验失败的 400 响应增加安全字段明细。
165 lines
5.3 KiB
Go
165 lines
5.3 KiB
Go
package request
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"reflect"
|
|
"regexp"
|
|
"strings"
|
|
|
|
failure "git.zhangdeman.cn/github/ginframework/internal/failure"
|
|
"github.com/go-playground/validator/v10"
|
|
)
|
|
|
|
var (
|
|
namespaceIndices = regexp.MustCompile(`\[[^\]]*\]`)
|
|
)
|
|
|
|
// FieldError 是允许公开的字段约束提示,不包含原始值或校验参数。
|
|
type FieldError struct {
|
|
Field string `json:"field" dc:"声明中的公开字段路径,集合下标统一为 []"`
|
|
Rule string `json:"rule" dc:"服务端声明的校验规则名,不包含参数或输入值"`
|
|
Message string `json:"message" dc:"安全提示,可由字段静态 err 标签指定"`
|
|
}
|
|
|
|
// ValidationDetails 是统一 400 响应中允许公开的字段错误数据。
|
|
type ValidationDetails struct {
|
|
Fields []FieldError `json:"fields" dc:"按校验器顺序排列的安全字段错误"`
|
|
}
|
|
|
|
// ValidationError 保留原生 validator 原因链及独立的公开提示。
|
|
type ValidationError struct {
|
|
Fields []FieldError `json:"fields" dc:"不包含凭据或客户端值的字段级提示"`
|
|
cause error `dc:"已在可信调用上下文分类记录的原始错误链"`
|
|
}
|
|
|
|
// Error 返回安全摘要。
|
|
// 返回:固定的校验失败说明,不输出原始值或内部结构体命名。
|
|
func (e *ValidationError) Error() string { return "request validation failed" }
|
|
|
|
// Unwrap 保留 validator 的错误原因。
|
|
// 返回:已记录的内部场景错误,支持继续 errors.As 到原生 ValidationErrors。
|
|
func (e *ValidationError) Unwrap() error { return e.cause }
|
|
|
|
// Code 返回所属校验失败场景码。
|
|
// 返回:内部场景码,不作为公开业务错误码。
|
|
func (e *ValidationError) Code() int { return CodeFormValidate1 }
|
|
|
|
// validationResult 在校验源头分类并提取静态声明中的安全字段描述。
|
|
// 入参:ctx 为标准上下文,receiver 为校验目标,err 为原生校验结果。
|
|
// 返回:成功时为 nil,字段失败为 ValidationError,其他失败保留原始原因。
|
|
func validationResult(ctx context.Context, receiver any, err error) error {
|
|
if err == nil {
|
|
return nil
|
|
}
|
|
classified := failure.WrapContext(ctx, CodeFormValidate1, "validate request fields failed", err)
|
|
var (
|
|
fields validator.ValidationErrors
|
|
)
|
|
if !errors.As(err, &fields) {
|
|
return classified
|
|
}
|
|
public := make([]FieldError, 0, len(fields))
|
|
for _, field := range fields {
|
|
name, message := fieldDescription(reflect.TypeOf(receiver), field.StructNamespace())
|
|
rule := field.Tag()
|
|
if message == "" {
|
|
message = validationMessage(rule)
|
|
}
|
|
public = append(public, FieldError{Field: name, Rule: rule, Message: message})
|
|
}
|
|
return &ValidationError{Fields: public, cause: classified}
|
|
}
|
|
|
|
// fieldDescription 只沿静态类型寻找公开名称,屏蔽动态 Map 键及集合下标。
|
|
// 入参:root 为 Form 类型,namespace 为校验器返回的字段路径。
|
|
// 返回:公开字段路径和字段 err 标签;无法映射或显式隐藏时使用 request 与通用提示。
|
|
func fieldDescription(root reflect.Type, namespace string) (string, string) {
|
|
for root != nil && root.Kind() == reflect.Ptr {
|
|
root = root.Elem()
|
|
}
|
|
if root == nil || root.Kind() != reflect.Struct {
|
|
return "request", ""
|
|
}
|
|
namespace = strings.TrimPrefix(namespace, root.Name()+".")
|
|
parts := strings.Split(namespaceIndices.ReplaceAllString(namespace, "[]"), ".")
|
|
var (
|
|
names []string
|
|
message string
|
|
)
|
|
current := root
|
|
for _, part := range parts {
|
|
for current.Kind() == reflect.Ptr {
|
|
current = current.Elem()
|
|
}
|
|
if current.Kind() != reflect.Struct {
|
|
return "request", ""
|
|
}
|
|
identifier := strings.SplitN(part, "[", 2)[0]
|
|
field, ok := current.FieldByName(identifier)
|
|
if !ok || field.PkgPath != "" && !field.Anonymous {
|
|
return "request", ""
|
|
}
|
|
suffix := strings.TrimPrefix(part, identifier)
|
|
if strings.ReplaceAll(suffix, "[]", "") != "" {
|
|
return "request", ""
|
|
}
|
|
label := ""
|
|
for _, tag := range []string{"json", "form", "uri"} {
|
|
candidate := strings.SplitN(field.Tag.Get(tag), ",", 2)[0]
|
|
if candidate == "-" {
|
|
return "request", ""
|
|
}
|
|
if candidate != "" {
|
|
label = candidate
|
|
break
|
|
}
|
|
}
|
|
if label == "" && !field.Anonymous {
|
|
label = field.Name
|
|
}
|
|
if label != "" {
|
|
names = append(names, label+suffix)
|
|
}
|
|
current = field.Type
|
|
for i := 0; i < strings.Count(suffix, "[]"); i++ {
|
|
for current.Kind() == reflect.Ptr {
|
|
current = current.Elem()
|
|
}
|
|
switch current.Kind() {
|
|
case reflect.Map, reflect.Array, reflect.Slice:
|
|
current = current.Elem()
|
|
default:
|
|
return "request", ""
|
|
}
|
|
}
|
|
message = field.Tag.Get("err")
|
|
}
|
|
if len(names) == 0 {
|
|
return "request", ""
|
|
}
|
|
return strings.Join(names, "."), message
|
|
}
|
|
|
|
// validationMessage 将常见规则转成不暴露输入或限制参数的安全说明。
|
|
// 入参:rule 为服务端校验规则名。
|
|
// 返回:英文缺省提示,自定义规则返回通用提示。
|
|
func validationMessage(rule string) string {
|
|
switch rule {
|
|
case "required", "required_if", "required_with", "required_without":
|
|
return "This field is required"
|
|
case "email":
|
|
return "Invalid email address"
|
|
case "min", "gte", "gt":
|
|
return "Value is below the allowed minimum"
|
|
case "max", "lte", "lt":
|
|
return "Value exceeds the allowed maximum"
|
|
case "len":
|
|
return "Invalid length"
|
|
case "oneof":
|
|
return "Value is not allowed"
|
|
default:
|
|
return "Invalid value"
|
|
}
|
|
}
|