1 parent
568e516b1a
commit
7ea7b153a2
10 files changed
+595
-46
No files matched your search
+24
-2
@@ -35,7 +35,9 @@ go mod tidy
|
||||
| `database/sqllog` | GORM 官方 Trace、MySQL 错误号/SQLSTATE 与 SQL 脱敏 | 自建原生 GORM 的可选日志适配 |
|
||||
| `redis` | 原生 Redis 客户端创建与探测 | 应用装配根 |
|
||||
| `redis/commandlog` | 官方 Hook 与 Pipeline 执行观测 | 自建原生 Redis 的可选日志适配 |
|
||||
| `http` | Gin Server、Form/Meta、响应、可信注入、健康检查、合作式预算、OpenAPI 契约与排空 | HTTP 入口 |
|
||||
| `http` | Gin Server、Form/Meta、响应、可信注入(含独立 InjectTrustedFields)、健康检查、合作式预算、OpenAPI 契约与排空 | HTTP 入口 |
|
||||
| `http/accesslog` | 安全头/数据副本、限长摘要与同步输出回调 | 可选访问日志 |
|
||||
| `http/recovery` | panic 捕获、安全诊断及可定制响应 | 可选恢复边界,Server 内置复用 |
|
||||
| `http/cors` | 来源匹配、凭据、预检、Vary 和显式授权回调 | HTTP 启动期可选中间件 |
|
||||
| `http/scalar` | 内嵌 Scalar 页面与脚本 | 文档展示的可选包 |
|
||||
| `ratelimit` | 内存/Redis 额度执行及重置 | 应用创建执行器,提供 Key 与额度 |
|
||||
@@ -109,7 +111,7 @@ if err = server.Group("/api", nil, &Example{}); err != nil {
|
||||
|
||||
Form 的 default tag 延续 go-defaults 行为,标量零值可能被认为缺省;需区分“未传”和“显式零值”时使用指针并补对应测试。没有 JSON 全字段存在性跟踪。
|
||||
|
||||
自定义原生 Gin Handler 可使用 `request.Form.Parse(ctx, &form)` 一次完成绑定、默认值和校验;若要在中间注入可信字段,顺序是 `Bind → defaults.SetDefaults(&form) → 应用显式注入可信字段 → ValidateContext(ctx.Request.Context(), &form)`,不能再重复 Parse。这里 defaults 是 github.com/mcuadros/go-defaults;Bind 和 ValidateContext 本身不会设置默认值。Validate(receiver) 保留为无请求来源的兼容入口;HTTP/Worker 的显式校验优先使用 ValidateContext,保留标准上下文诊断。自定义字段规则通过 `request.RegisterValidation` 在启动期登记,规则函数使用 validator/v10 原生类型。
|
||||
自定义原生 Gin Handler 可使用 `request.Form.Parse(ctx, &form)` 一次完成绑定、默认值和校验;若要在中间注入可信字段,顺序是 `Bind → defaults.SetDefaults(&form) → framework.InjectTrustedFields(ctx, &form, rules) → ValidateContext(ctx.Request.Context(), &form)`,不能再重复 Parse。这里 defaults 是 github.com/mcuadros/go-defaults;Bind 和 ValidateContext 本身不会设置默认值。Validate(receiver) 保留为无请求来源的兼容入口;HTTP/Worker 的显式校验优先使用 ValidateContext,保留标准上下文诊断。自定义字段规则通过 `request.RegisterValidation` 在启动期登记,规则函数使用 validator/v10 原生类型。
|
||||
|
||||
字段提示使用 json/form/uri 中声明的公开名称,嵌入 Input 不增加对象层级,集合位置统一为 [],例如 profile.email、items[].email。返回 rule 但不返回校验参数、原始输入、Map 键和内部 Form 类型名;常见规则有默认英文提示,可用字段静态 err 标签提供安全文案。未知映射使用 request。调用方可通过 errors.As 继续识别 request.ValidationError 和底层 validator.ValidationErrors。
|
||||
|
||||
@@ -137,6 +139,8 @@ options := framework.Options{
|
||||
|
||||
示例 authenticate 是应用自身函数,必须验证凭据并在失败时终止处理。每条注入规则执行前会清空客户端旧值,nil 结果表示清空,读取失败不会回退使用客户端数据;返回值类型必须与目标字段匹配。资源归属、权限及业务状态仍由业务层检查。
|
||||
|
||||
原生 Gin Handler 可在绑定和默认值之后调用 `framework.InjectTrustedFields(ctx, &form, rules)`,成功后再调用 `request.Form.ValidateContext(ctx.Request.Context(), &form)`,不得重复 Parse。该入口与 Server 共用实现;receiver 必须是非 nil 可写结构体指针,支持匿名嵌入指针的按需初始化。匹配字段的回调不能为 nil;不存在或歧义字段跳过且不调用回调,规则按 Go 名称排序。规则 map 在调用期间不得修改,表单须由当前调用独占。函数不持有资源或修改规则;失败会保留已执行的赋值,应用必须中止使用该表单,不回退到客户端值。需要拒绝 nil 结果时由应用读取回调返回错误;框架继续保持 nil 表示清空的既有契约。
|
||||
|
||||
默认不信任代理转发头。确需读取代理地址时通过 Config.TrustedProxies 显式配置可信代理名单。库生成 request_id/trace_id,不接受客户端同名头作为可信来源。
|
||||
|
||||
### 4.3 公开错误
|
||||
@@ -448,3 +452,21 @@ make race-check
|
||||
make verify 包含 docs-check、格式、架构依赖、vet、build、test 和固定版本 Staticcheck;并发/生命周期变化再执行 race-check。文档门禁校验公开包清单及仓库相对链接,不自动证明业务含义和示例预算正确。
|
||||
|
||||
消费项目接入后核对真实路由、公开响应、身份覆盖、取消、配置、日志脱敏和退出顺序。真实 MySQL、供应商、代理及大文件吞吐按消费环境验证,不把本地回归等同于线上通过。
|
||||
|
||||
|
||||
## 可选访问日志与 panic 恢复
|
||||
|
||||
`http/accesslog.New(config, options)` 只采集副本,不读取 Request.Body、不包装 Writer,也不缓冲 SSE。Config 只保存名单、额外 RedactKeys 和摘要阈值,构造时复制名单;Options 提供 RecordRequest/RecordResponse 过滤、Filter 共同附加条件、RequestBody/ResponseBody 已解析数据来源及 Emit 输出回调。Emit 为 nil 完全禁用采集;正文来源为 nil 不采集正文。应用负责输出日志实例和业务成功判定,不得在数据回调消费未恢复的流。默认进入策略为非 OPTIONS 且 JSON 请求/Accept 或无扩展名路径;默认完成策略仅 JSON Content-Type。各阶段策略独立,可显式覆盖。
|
||||
|
||||
敏感请求头不可通过允许名单重新启用。数据复用 storagevalue.Safe,支持结构体、集合和 JSON 字符串副本;额外敏感键忽略大小写并在副本中替换。未配置或非正数阈值为 4 KiB,超过时仅输出 truncated、original_bytes、sha256,摘要基于脱敏后数据。阈值限制日志输出,不是读取/内存上限;应用须限制数据规模,不传入不可信且无界的对象。Record 含进入/完成标记、时间、单调耗时、状态、头、查询首值和正文;不含原始 URL 查询串。同步 Emit 可附加可信诊断和业务字段,框架不关闭应用日志资源。原生 Server 的 Options.AccessLogger 仍仅记录协议元数据;安装该可选中间件时按需关闭前者避免重复完成流水。
|
||||
|
||||
`http/recovery.New(recovery.Options{Report: ..., Respond: ...})` 捕获当前请求协程 panic。Incident 仅保留动态类型和一次 debug.Stack,不携带原始 panic 值;Report 为 nil 使用框架 default 安全错误日志,Respond 为 nil 使用通用 JSON 500。Report/Respond 为同步应用回调,应用负责并发安全和诊断脱敏。先报告并 Abort,再仅在响应未提交时调用 Respond;已写出响应或 SSE Flush 后不会追加 JSON 或更改状态。普通 error 不进入恢复,业务创建的子协程须自行管理。Server 已通过该实现保留原有错误映射;应用嵌套安装时由最近的恢复边界处理,不重复记录同一 panic。无后台任务和待关闭资源。
|
||||
|
||||
```go
|
||||
server.Use(accesslog.New(accesslog.Config{RedactKeys: []string{"config_value"}}, accesslog.Options{
|
||||
Emit: func(ctx *gin.Context, record accesslog.Record) {
|
||||
output.Info("HTTP access recorded", logger.Fields(record))
|
||||
},
|
||||
}))
|
||||
// output 为应用管理的 *zap.Logger;此示例默认不读取或记录正文。
|
||||
```
|
||||
@@ -0,0 +1,175 @@
|
||||
// Package accesslog 为 Gin 请求生成安全日志副本,不包装 Writer 或缓冲流式响应。
|
||||
package accesslog
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"path"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.zhangdeman.cn/zhangdeman/ginframework/logger/storagevalue"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const defaultBodyBytes = 4 << 10
|
||||
|
||||
// Config 仅描述日志选择、脱敏和输出摘要上限,不控制真实请求大小。
|
||||
type Config struct {
|
||||
RequestHeaderList []string `json:"request_header_list" dc:"请求头允许名单,空表示除敏感头外全部"`
|
||||
IgnoreRequestHeaderList []string `json:"ignore_request_header_list" dc:"额外忽略的请求头,忽略大小写"`
|
||||
ResponseHeaderList []string `json:"response_header_list" dc:"响应头允许名单,空表示除敏感头外全部"`
|
||||
IgnoreResponseHeaderList []string `json:"ignore_response_header_list" dc:"额外忽略的响应头,忽略大小写"`
|
||||
RedactKeys []string `json:"redact_keys" dc:"除框架凭据字段外额外隐藏的字段名,忽略大小写"`
|
||||
MaxRequestBodyBytes int `json:"max_request_body_bytes" dc:"请求数据的日志摘要阈值,非正数采用四 KiB"`
|
||||
MaxResponseBodyBytes int `json:"max_response_body_bytes" dc:"响应数据的日志摘要阈值,非正数采用四 KiB"`
|
||||
}
|
||||
|
||||
// Record 是一次请求进入或完成时的安全日志副本。
|
||||
type Record struct {
|
||||
Request bool `json:"request" dc:"是否为请求进入记录,false 为请求完成"`
|
||||
StartedAt time.Time `json:"started_at" dc:"本地请求进入时间"`
|
||||
FinishedAt time.Time `json:"finished_at" dc:"完成时间,进入记录为零值"`
|
||||
Duration time.Duration `json:"duration" dc:"完成时的单调时钟耗时,进入记录为零"`
|
||||
Status int `json:"status" dc:"当前响应状态"`
|
||||
Header http.Header `json:"header" dc:"经过过滤且与原始头隔离的副本"`
|
||||
Query any `json:"query" dc:"请求查询参数的脱敏副本,仅进入记录设置"`
|
||||
Body any `json:"body" dc:"应用提供的异构请求或响应数据的脱敏副本,未提供回调为 nil"`
|
||||
}
|
||||
|
||||
// Options 显式提供日志策略、已解析数据来源和最终输出。
|
||||
type Options struct {
|
||||
Filter func(*gin.Context) bool `json:"-" dc:"请求和响应的共同附加过滤条件,nil 不过滤"`
|
||||
RecordRequest func(*gin.Context) bool `json:"-" dc:"进入记录策略,nil 使用 API 请求判断"`
|
||||
RecordResponse func(*gin.Context) bool `json:"-" dc:"完成记录策略,nil 仅记录 JSON 响应"`
|
||||
RequestBody func(*gin.Context) any `json:"-" dc:"应用提供已解析请求数据,nil 不读取 Body"`
|
||||
ResponseBody func(*gin.Context) any `json:"-" dc:"应用提供响应数据,nil 不采集响应正文"`
|
||||
Emit func(*gin.Context, Record) `json:"-" dc:"同步消费安全记录,nil 禁用采集"`
|
||||
}
|
||||
|
||||
// New 复制名单并创建无资源所有权的访问日志中间件。
|
||||
// 入参:config 为数据配置,options 为同步回调;回调不得修改 Writer 或消费未恢复的请求流。
|
||||
// 返回:Gin 中间件;不会读取 Request.Body、替换 Writer、阻止 Flush 或接管日志关闭。
|
||||
// 正文仅在显式数据回调存在时采集;超过阈值只保留脱敏后的长度和 SHA256,不返回部分原文。
|
||||
// 阈值限制日志输出,不是读取或内存上限;应用须约束传入数据规模。
|
||||
func New(config Config, options Options) gin.HandlerFunc {
|
||||
requestHeaders := append([]string(nil), config.RequestHeaderList...)
|
||||
responseHeaders := append([]string(nil), config.ResponseHeaderList...)
|
||||
requestIgnored := headerSet(config.IgnoreRequestHeaderList)
|
||||
responseIgnored := headerSet(config.IgnoreResponseHeaderList)
|
||||
redact := make(map[string]bool, len(config.RedactKeys))
|
||||
for _, key := range config.RedactKeys {
|
||||
redact[strings.ToLower(key)] = true
|
||||
}
|
||||
requestLimit, responseLimit := config.MaxRequestBodyBytes, config.MaxResponseBodyBytes
|
||||
if requestLimit <= 0 {
|
||||
requestLimit = defaultBodyBytes
|
||||
}
|
||||
if responseLimit <= 0 {
|
||||
responseLimit = defaultBodyBytes
|
||||
}
|
||||
return func(ctx *gin.Context) {
|
||||
if options.Emit == nil {
|
||||
ctx.Next()
|
||||
return
|
||||
}
|
||||
start := time.Now()
|
||||
recordRequest := ctx.Request.Method != http.MethodOptions && (strings.Contains(strings.ToLower(ctx.GetHeader("Content-Type")), "json") || strings.Contains(strings.ToLower(ctx.GetHeader("Accept")), "json") || path.Ext(ctx.Request.URL.Path) == "")
|
||||
if options.RecordRequest != nil {
|
||||
recordRequest = options.RecordRequest(ctx)
|
||||
}
|
||||
if recordRequest && (options.Filter == nil || options.Filter(ctx)) {
|
||||
query := make(map[string]string)
|
||||
for key, values := range ctx.Request.URL.Query() {
|
||||
if len(values) > 0 {
|
||||
query[key] = values[0]
|
||||
} else {
|
||||
query[key] = ""
|
||||
}
|
||||
}
|
||||
record := Record{Request: true, StartedAt: start, Status: ctx.Writer.Status(), Header: selectHeaders(ctx.Request.Header, requestHeaders, requestIgnored), Query: summarize(query, requestLimit, redact)}
|
||||
if options.RequestBody != nil {
|
||||
record.Body = summarize(options.RequestBody(ctx), requestLimit, redact)
|
||||
}
|
||||
options.Emit(ctx, record)
|
||||
}
|
||||
ctx.Next()
|
||||
recordResponse := strings.Contains(strings.ToLower(ctx.Writer.Header().Get("Content-Type")), "application/json")
|
||||
if options.RecordResponse != nil {
|
||||
recordResponse = options.RecordResponse(ctx)
|
||||
}
|
||||
if recordResponse && (options.Filter == nil || options.Filter(ctx)) {
|
||||
record := Record{StartedAt: start, FinishedAt: time.Now(), Duration: time.Since(start), Status: ctx.Writer.Status(), Header: selectHeaders(ctx.Writer.Header(), responseHeaders, responseIgnored)}
|
||||
if options.ResponseBody != nil {
|
||||
record.Body = summarize(options.ResponseBody(ctx), responseLimit, redact)
|
||||
}
|
||||
options.Emit(ctx, record)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// headerSet 建立构造期忽略名单;入参为额外头名称,返回独立只读索引。
|
||||
func headerSet(names []string) map[string]bool {
|
||||
result := map[string]bool{"authorization": true, "proxy-authorization": true, "cookie": true, "set-cookie": true, "x-api-key": true, "x-auth-token": true, "x-access-token": true}
|
||||
for _, name := range names {
|
||||
result[strings.ToLower(strings.TrimSpace(name))] = true
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// selectHeaders 返回允许且非敏感头的副本;入参为原始头、允许名单和忽略索引。
|
||||
func selectHeaders(header http.Header, selected []string, ignored map[string]bool) http.Header {
|
||||
result := make(http.Header)
|
||||
for key, values := range header {
|
||||
if ignored[strings.ToLower(key)] || storagevalue.Sensitive(key) {
|
||||
continue
|
||||
}
|
||||
allowed := len(selected) == 0
|
||||
for _, name := range selected {
|
||||
if strings.EqualFold(strings.TrimSpace(name), key) {
|
||||
allowed = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if allowed {
|
||||
result[key] = append([]string(nil), values...)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// redactKeys 隐藏 Safe 副本中的应用额外敏感键;入参为副本和构造期索引,返回处理后的副本。
|
||||
func redactKeys(value any, keys map[string]bool) any {
|
||||
switch typed := value.(type) {
|
||||
case map[string]any:
|
||||
for key, item := range typed {
|
||||
if keys[strings.ToLower(key)] {
|
||||
typed[key] = "[REDACTED]"
|
||||
} else {
|
||||
typed[key] = redactKeys(item, keys)
|
||||
}
|
||||
}
|
||||
case []any:
|
||||
for index, item := range typed {
|
||||
typed[index] = redactKeys(item, keys)
|
||||
}
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
// summarize 先生成独立脱敏副本,再应用摘要阈值;入参为异构数据、阈值和额外敏感键。
|
||||
// 返回:安全副本或长度与摘要;编码异常时只返回安全标记,不返回原对象。
|
||||
func summarize(value any, limit int, keys map[string]bool) any {
|
||||
safe := redactKeys(storagevalue.Safe(value), keys)
|
||||
encoded, err := json.Marshal(safe)
|
||||
if err != nil {
|
||||
return "[UNREPRESENTABLE]"
|
||||
}
|
||||
if len(encoded) <= limit {
|
||||
return safe
|
||||
}
|
||||
digest := sha256.Sum256(encoded)
|
||||
return map[string]any{"truncated": true, "original_bytes": len(encoded), "sha256": hex.EncodeToString(digest[:])}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package accesslog
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func TestSafeCopiesAndSnapshots(t *testing.T) {
|
||||
source := map[string]any{"password": "private-password", "config_value": "private-config", "items": []any{map[string]any{"token": "private-token"}}, "visible": "ok"}
|
||||
headers := []string{"X-Visible", "Authorization"}
|
||||
cfg := Config{RequestHeaderList: headers, RedactKeys: []string{"config_value"}, MaxResponseBodyBytes: 32}
|
||||
records := []Record{}
|
||||
engine := gin.New()
|
||||
engine.Use(New(cfg, Options{
|
||||
RequestBody: func(*gin.Context) any { return source },
|
||||
ResponseBody: func(*gin.Context) any { return map[string]any{"payload": strings.Repeat("x", 100)} },
|
||||
Emit: func(_ *gin.Context, r Record) { records = append(records, r) },
|
||||
}))
|
||||
headers[0] = "X-Later"
|
||||
cfg.RedactKeys[0] = "other"
|
||||
engine.POST("/api", func(ctx *gin.Context) {
|
||||
data, err := io.ReadAll(ctx.Request.Body)
|
||||
if err != nil || string(data) != "original-stream" {
|
||||
t.Fatalf("body altered: %s %v", data, err)
|
||||
}
|
||||
ctx.Header("Set-Cookie", "private-cookie")
|
||||
ctx.Header("Content-Type", "application/json")
|
||||
ctx.String(200, "ok")
|
||||
})
|
||||
req := httptest.NewRequest("POST", "/api?token=private-query", strings.NewReader("original-stream"))
|
||||
req.Header.Set("X-Visible", "yes")
|
||||
req.Header.Set("Authorization", "private-header")
|
||||
engine.ServeHTTP(httptest.NewRecorder(), req)
|
||||
if len(records) != 2 {
|
||||
t.Fatalf("records=%+v", records)
|
||||
}
|
||||
encoded, err := json.Marshal(records)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, secret := range []string{"private-password", "private-config", "private-token", "private-query", "private-header", "private-cookie"} {
|
||||
if strings.Contains(string(encoded), secret) {
|
||||
t.Fatalf("leaked %s", secret)
|
||||
}
|
||||
}
|
||||
if records[0].Header.Get("X-Visible") != "yes" || !strings.Contains(string(encoded), "sha256") {
|
||||
t.Fatalf("missing header or digest: %s", encoded)
|
||||
}
|
||||
records[0].Body.(map[string]any)["visible"] = "changed"
|
||||
if source["visible"] != "ok" || source["password"] != "private-password" {
|
||||
t.Fatal("source modified")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStreamingWriterAndIndependentPolicies(t *testing.T) {
|
||||
records := []Record{}
|
||||
engine := gin.New()
|
||||
engine.Use(New(Config{}, Options{RecordRequest: func(*gin.Context) bool { return false }, RecordResponse: func(*gin.Context) bool { return true }, Emit: func(_ *gin.Context, r Record) { records = append(records, r) }}))
|
||||
engine.GET("/events", func(ctx *gin.Context) { ctx.SSEvent("ready", "hello"); ctx.Writer.Flush() })
|
||||
out := httptest.NewRecorder()
|
||||
engine.ServeHTTP(out, httptest.NewRequest("GET", "/events", nil))
|
||||
if !out.Flushed || !strings.Contains(out.Body.String(), "hello") || len(records) != 1 || records[0].Request || records[0].Body != nil {
|
||||
t.Fatalf("stream changed: %+v %s", records, out.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestDefaultPoliciesAndDisabledCollector(t *testing.T) {
|
||||
for _, method := range []string{http.MethodGet, http.MethodOptions} {
|
||||
count := 0
|
||||
engine := gin.New()
|
||||
engine.Use(New(Config{}, Options{Filter: func(*gin.Context) bool { return true }, Emit: func(*gin.Context, Record) { count++ }}))
|
||||
engine.Handle(method, "/api", func(ctx *gin.Context) { ctx.Status(204) })
|
||||
engine.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(method, "/api", nil))
|
||||
expected := 1
|
||||
if method == http.MethodOptions {
|
||||
expected = 0
|
||||
}
|
||||
if count != expected {
|
||||
t.Fatalf("%s count=%d", method, count)
|
||||
}
|
||||
}
|
||||
engine := gin.New()
|
||||
engine.Use(New(Config{}, Options{RequestBody: func(*gin.Context) any { t.Fatal("disabled collector read"); return nil }}))
|
||||
engine.GET("/api", func(ctx *gin.Context) { ctx.Status(204) })
|
||||
engine.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "/api", nil))
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
// Package recovery 捕获 Gin 请求 panic,允许应用显式提供报告和响应协议。
|
||||
package recovery
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"runtime/debug"
|
||||
|
||||
"git.zhangdeman.cn/zhangdeman/ginframework/fault"
|
||||
"git.zhangdeman.cn/zhangdeman/ginframework/logger"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const codePanic = 900901
|
||||
|
||||
// Incident 只包含 panic 类型和单次采集的调用栈,不保存原始 panic 值。
|
||||
type Incident struct {
|
||||
Type string `json:"type" dc:"panic 动态类型,不调用其格式化方法"`
|
||||
Stack []byte `json:"-" dc:"本次恢复的单次调用栈,仅供内部诊断"`
|
||||
}
|
||||
|
||||
// Options 指定 panic 的诊断和安全响应边界。
|
||||
type Options struct {
|
||||
Report func(*gin.Context, Incident) `json:"-" dc:"同步记录一次 panic,nil 使用框架安全错误日志"`
|
||||
Respond func(*gin.Context) `json:"-" dc:"未提交响应时调用的安全响应函数,nil 返回通用 JSON 500"`
|
||||
}
|
||||
|
||||
// New 创建 panic 恢复中间件;入参为应用协议回调,返回 Gin Handler。
|
||||
// 仅恢复当前请求协程,不吞掉普通 error;报告后中止处理链。
|
||||
// 响应已提交(包括 SSE Flush)时不追加 JSON 或改写状态,仍报告并 Abort。
|
||||
// 不拥有日志资源;应用负责回调的并发安全和不泄漏诊断内容。
|
||||
func New(options Options) gin.HandlerFunc {
|
||||
return func(ctx *gin.Context) {
|
||||
defer func() {
|
||||
if recovered := recover(); recovered != nil {
|
||||
incident := Incident{Type: fmt.Sprintf("%T", recovered), Stack: debug.Stack()}
|
||||
ctx.Abort()
|
||||
if options.Report != nil {
|
||||
options.Report(ctx, incident)
|
||||
} else {
|
||||
logger.RecordErrorContext(ctx.Request.Context(), "recover HTTP handler panic", fault.New(codePanic, "recover HTTP handler panic", nil))
|
||||
}
|
||||
if ctx.Writer.Written() {
|
||||
return
|
||||
}
|
||||
if options.Respond != nil {
|
||||
options.Respond(ctx)
|
||||
} else {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"code": http.StatusInternalServerError, "message": "Internal Server Error"})
|
||||
}
|
||||
}
|
||||
}()
|
||||
ctx.Next()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package recovery
|
||||
|
||||
import (
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type sensitivePanic struct{}
|
||||
|
||||
func (sensitivePanic) String() string { panic("formatter must not be invoked") }
|
||||
|
||||
func TestCustomRecoveryAndCommittedStream(t *testing.T) {
|
||||
for _, stream := range []bool{false, true} {
|
||||
reports, responses := 0, 0
|
||||
engine := gin.New()
|
||||
engine.Use(New(Options{Report: func(_ *gin.Context, incident Incident) {
|
||||
reports++
|
||||
if !strings.Contains(incident.Type, "sensitivePanic") || !strings.Contains(string(incident.Stack), "TestCustomRecoveryAndCommittedStream") {
|
||||
t.Fatal("missing diagnostic")
|
||||
}
|
||||
}, Respond: func(ctx *gin.Context) { responses++; ctx.JSON(503, gin.H{"message": "safe"}) }}))
|
||||
engine.GET("/panic", func(ctx *gin.Context) {
|
||||
if stream {
|
||||
ctx.SSEvent("ready", "hello")
|
||||
ctx.Writer.Flush()
|
||||
}
|
||||
panic(sensitivePanic{})
|
||||
}, func(*gin.Context) { t.Fatal("continued after panic") })
|
||||
out := httptest.NewRecorder()
|
||||
engine.ServeHTTP(out, httptest.NewRequest("GET", "/panic", nil))
|
||||
if reports != 1 {
|
||||
t.Fatalf("reports=%d", reports)
|
||||
}
|
||||
if stream {
|
||||
if responses != 0 || out.Code != 200 || !out.Flushed || strings.Contains(out.Body.String(), "safe") {
|
||||
t.Fatal("stream rewritten")
|
||||
}
|
||||
} else if responses != 1 || out.Code != 503 {
|
||||
t.Fatal("custom response missing")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDefaultRecoveryHidesValue(t *testing.T) {
|
||||
engine := gin.New()
|
||||
engine.Use(New(Options{}))
|
||||
engine.GET("/panic", func(*gin.Context) { panic("private-token") })
|
||||
out := httptest.NewRecorder()
|
||||
engine.ServeHTTP(out, httptest.NewRequest("GET", "/panic", nil))
|
||||
if out.Code != 500 || strings.Contains(out.Body.String(), "private-token") {
|
||||
t.Fatalf("unsafe default: %s", out.Body.String())
|
||||
}
|
||||
}
|
||||
@@ -59,6 +59,7 @@ const (
|
||||
codeOpenAPIResponse = 900441
|
||||
codeServeUntilConfig = 900442
|
||||
codeServeUntilCanceled = 900443
|
||||
codeTrustedForm = 900444
|
||||
)
|
||||
|
||||
// PublicError 是业务显式允许公开的错误,不包含原始原因文本。
|
||||
|
||||
+1
-36
@@ -202,42 +202,7 @@ func isNil(value reflect.Value) bool {
|
||||
// 入参:ctx 为认证后的请求,form 为可写结构体。
|
||||
// 返回:读取或类型不匹配错误,绝不回退到客户端值。
|
||||
func (s *Server) inject(ctx *gin.Context, form reflect.Value) error {
|
||||
for _, name := range s.trustedFieldNames {
|
||||
definition, exists := form.Type().FieldByName(name)
|
||||
if !exists {
|
||||
continue
|
||||
}
|
||||
field := form
|
||||
for _, index := range definition.Index {
|
||||
if field.Kind() == reflect.Ptr {
|
||||
if field.IsNil() {
|
||||
if !field.CanSet() {
|
||||
return failure.WrapContext(ctx.Request.Context(), codeInject, "resolve trusted field failed", errors.New("embedded field is not writable"))
|
||||
}
|
||||
field.Set(reflect.New(field.Type().Elem()))
|
||||
}
|
||||
field = field.Elem()
|
||||
}
|
||||
field = field.Field(index)
|
||||
}
|
||||
if !field.CanSet() {
|
||||
return failure.WrapContext(ctx.Request.Context(), codeInject, "resolve trusted field failed", errors.New("trusted field is not writable"))
|
||||
}
|
||||
field.SetZero()
|
||||
value, err := s.options.TrustedFields[name](ctx)
|
||||
if err != nil {
|
||||
return failure.WrapContext(ctx.Request.Context(), codeTrustedRead, "read trusted field failed", err)
|
||||
}
|
||||
if value == nil {
|
||||
continue
|
||||
}
|
||||
source := reflect.ValueOf(value)
|
||||
if !source.Type().AssignableTo(field.Type()) {
|
||||
return failure.WrapContext(ctx.Request.Context(), codeTrustedType, "assign trusted field failed", errors.New("trusted field type mismatch"))
|
||||
}
|
||||
field.Set(source)
|
||||
}
|
||||
return nil
|
||||
return injectTrustedFields(ctx, form, s.options.TrustedFields, s.trustedFieldNames)
|
||||
}
|
||||
|
||||
// commit 用候选 Gin 引擎验证完整路由表,成功后一次替换,避免部分注册。
|
||||
|
||||
+9
-8
@@ -12,6 +12,7 @@ import (
|
||||
|
||||
"git.zhangdeman.cn/zhangdeman/ginframework/diagnostic"
|
||||
"git.zhangdeman.cn/zhangdeman/ginframework/fault"
|
||||
"git.zhangdeman.cn/zhangdeman/ginframework/http/recovery"
|
||||
failure "git.zhangdeman.cn/zhangdeman/ginframework/internal/failure"
|
||||
"git.zhangdeman.cn/zhangdeman/ginframework/logger"
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -193,13 +194,6 @@ func (s *Server) initialize(ctx *gin.Context) {
|
||||
ctx.Request = ctx.Request.WithContext(diagnostic.With(ctx.Request.Context(), diagnostic.Snapshot{RequestID: id, TraceID: id, URI: ctx.Request.URL.Path, Method: ctx.Request.Method, Service: s.config.Service}))
|
||||
ctx.Header("X-Request-ID", id)
|
||||
defer func() {
|
||||
if recovered := recover(); recovered != nil {
|
||||
// panic 值可能含凭据,不写入响应或日志。
|
||||
panicError := fault.New(codePanic, "recover HTTP handler panic", nil)
|
||||
logger.RecordErrorContext(ctx.Request.Context(), "recover HTTP handler panic", panicError)
|
||||
s.writeResult(ctx, nil, panicError, http.StatusInternalServerError)
|
||||
ctx.Abort()
|
||||
}
|
||||
if ctx.Request.MultipartForm != nil {
|
||||
if err := ctx.Request.MultipartForm.RemoveAll(); err != nil {
|
||||
logger.RecordErrorContext(ctx.Request.Context(), "remove multipart temporary files failed", fault.New(codeMultipartCleanup, "remove multipart temporary files failed", err))
|
||||
@@ -209,5 +203,12 @@ func (s *Server) initialize(ctx *gin.Context) {
|
||||
s.options.AccessLogger.Info("HTTP request completed", zap.String("trace_id", id), zap.String("uri", ctx.Request.URL.Path), zap.String("method", ctx.Request.Method), zap.Int("status", ctx.Writer.Status()), zap.Duration("duration", time.Since(start)))
|
||||
}
|
||||
}()
|
||||
ctx.Next()
|
||||
recovery.New(recovery.Options{
|
||||
Report: func(ctx *gin.Context, _ recovery.Incident) {
|
||||
logger.RecordErrorContext(ctx.Request.Context(), "recover HTTP handler panic", fault.New(codePanic, "recover HTTP handler panic", nil))
|
||||
},
|
||||
Respond: func(ctx *gin.Context) {
|
||||
s.writeResult(ctx, nil, fault.New(codePanic, "recover HTTP handler panic", nil), http.StatusInternalServerError)
|
||||
},
|
||||
})(ctx)
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"sort"
|
||||
|
||||
failure "git.zhangdeman.cn/zhangdeman/ginframework/internal/failure"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// InjectTrustedFields 为原生 Gin Handler 注入可信公共字段,与 Server 的 Controller 共用赋值流程。
|
||||
// 入参:ctx 必须含有效 Request;receiver 为非 nil 的可写结构体指针;rules 按 Go 字段名提供可信读取函数。
|
||||
// 返回:表单、字段或读取错误,保留原因链;成功返回 nil。
|
||||
// 缺失或歧义字段跳过;规则按名称排序,按需分配匿名嵌入指针。
|
||||
// 每个匹配字段读取前清零,nil 返回表示保持零值;失败后不得继续使用该表单,已注入字段不会回滚。
|
||||
// 调用方须保证调用期间独占表单,规则 map 不被并发修改;绑定和默认值在调用前完成,校验在成功后执行一次。
|
||||
func InjectTrustedFields(ctx *gin.Context, receiver any, rules map[string]TrustedField) error {
|
||||
form := reflect.ValueOf(receiver)
|
||||
for form.IsValid() && form.Kind() == reflect.Ptr {
|
||||
if form.IsNil() {
|
||||
break
|
||||
}
|
||||
form = form.Elem()
|
||||
}
|
||||
if !form.IsValid() || form.Kind() != reflect.Struct || !form.CanSet() {
|
||||
return failure.WrapContext(ctx.Request.Context(), codeTrustedForm, "validate trusted form failed", errors.New("trusted form must be a writable non-nil struct pointer"))
|
||||
}
|
||||
names := make([]string, 0, len(rules))
|
||||
for name := range rules {
|
||||
names = append(names, name)
|
||||
}
|
||||
sort.Strings(names)
|
||||
return injectTrustedFields(ctx, form, rules, names)
|
||||
}
|
||||
|
||||
// injectTrustedFields 对可写 Form 执行有序覆盖,供原生 Controller 与显式注入共同使用。
|
||||
// 入参:ctx 含有效 Request;form 为已校验的可写结构体;rules 为可信读取函数;names 为排序后的规则名。
|
||||
// 返回:字段不可写、规则为空、读取及类型错误;字段不存在时不执行对应读取函数。
|
||||
func injectTrustedFields(ctx *gin.Context, form reflect.Value, rules map[string]TrustedField, names []string) error {
|
||||
for _, name := range names {
|
||||
definition, exists := form.Type().FieldByName(name)
|
||||
if !exists {
|
||||
continue
|
||||
}
|
||||
field := form
|
||||
for _, index := range definition.Index {
|
||||
if field.Kind() == reflect.Ptr {
|
||||
if field.IsNil() {
|
||||
if !field.CanSet() {
|
||||
return failure.WrapContext(ctx.Request.Context(), codeInject, "resolve trusted field failed", fmt.Errorf("%s: embedded field is not writable", name))
|
||||
}
|
||||
field.Set(reflect.New(field.Type().Elem()))
|
||||
}
|
||||
field = field.Elem()
|
||||
}
|
||||
field = field.Field(index)
|
||||
}
|
||||
if !field.CanSet() {
|
||||
return failure.WrapContext(ctx.Request.Context(), codeInject, "resolve trusted field failed", fmt.Errorf("%s: trusted field is not writable", name))
|
||||
}
|
||||
field.SetZero()
|
||||
if rules[name] == nil {
|
||||
return failure.WrapContext(ctx.Request.Context(), codeTrustedRule, "validate trusted field rule failed", fmt.Errorf("%s: trusted field callback is required", name))
|
||||
}
|
||||
value, err := rules[name](ctx)
|
||||
if err != nil {
|
||||
return failure.WrapContext(ctx.Request.Context(), codeTrustedRead, "read trusted field failed", err)
|
||||
}
|
||||
if value == nil {
|
||||
continue
|
||||
}
|
||||
source := reflect.ValueOf(value)
|
||||
if !source.Type().AssignableTo(field.Type()) {
|
||||
return failure.WrapContext(ctx.Request.Context(), codeTrustedType, "assign trusted field failed", fmt.Errorf("%s: trusted field type mismatch", name))
|
||||
}
|
||||
field.Set(source)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http/httptest"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type TrustedIdentity struct{ UserID uint }
|
||||
type trustedForm struct {
|
||||
*TrustedIdentity
|
||||
Other string
|
||||
hidden string
|
||||
}
|
||||
|
||||
func TestInjectTrustedFieldsSharedFlow(t *testing.T) {
|
||||
for _, native := range []bool{false, true} {
|
||||
ctx, _ := gin.CreateTestContext(httptest.NewRecorder())
|
||||
ctx.Request = httptest.NewRequest("GET", "/", nil)
|
||||
seen := []string{}
|
||||
rules := map[string]TrustedField{
|
||||
"UserID": func(*gin.Context) (any, error) { seen = append(seen, "UserID"); return uint(7), nil },
|
||||
"Other": func(*gin.Context) (any, error) { seen = append(seen, "Other"); return "ok", nil },
|
||||
"Missing": func(*gin.Context) (any, error) { t.Fatal("missing field callback called"); return nil, nil },
|
||||
}
|
||||
form := &trustedForm{}
|
||||
var (
|
||||
err error
|
||||
)
|
||||
if native {
|
||||
server, createErr := NewServer(Config{}, Options{TrustedFields: rules})
|
||||
if createErr != nil {
|
||||
t.Fatal(createErr)
|
||||
}
|
||||
err = server.inject(ctx, reflect.ValueOf(form).Elem())
|
||||
} else {
|
||||
err = InjectTrustedFields(ctx, form, rules)
|
||||
}
|
||||
if err != nil || form.TrustedIdentity == nil || form.UserID != 7 || form.Other != "ok" || !reflect.DeepEqual(seen, []string{"Other", "UserID"}) {
|
||||
t.Fatalf("native=%v form=%+v seen=%v err=%v", native, form, seen, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestInjectTrustedFieldsClearsBeforeFailure(t *testing.T) {
|
||||
cause := errors.New("private cause")
|
||||
for _, name := range []string{"nil result", "nil callback", "wrong type", "read error"} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
ctx, _ := gin.CreateTestContext(httptest.NewRecorder())
|
||||
ctx.Request = httptest.NewRequest("GET", "/", nil)
|
||||
form := &TrustedIdentity{UserID: 999}
|
||||
reader := TrustedField(func(*gin.Context) (any, error) {
|
||||
if form.UserID != 0 {
|
||||
t.Fatal("untrusted value visible to getter")
|
||||
}
|
||||
return nil, nil
|
||||
})
|
||||
switch name {
|
||||
case "nil callback":
|
||||
reader = nil
|
||||
case "wrong type":
|
||||
reader = func(*gin.Context) (any, error) { return "secret", nil }
|
||||
case "read error":
|
||||
reader = func(*gin.Context) (any, error) { return nil, cause }
|
||||
}
|
||||
err := InjectTrustedFields(ctx, form, map[string]TrustedField{"UserID": reader})
|
||||
if form.UserID != 0 || (name == "nil result") != (err == nil) {
|
||||
t.Fatalf("form=%+v err=%v", form, err)
|
||||
}
|
||||
if name == "read error" && !errors.Is(err, cause) {
|
||||
t.Fatal("cause lost")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestInjectTrustedFieldsRejectsInvalidTargets(t *testing.T) {
|
||||
var (
|
||||
nilForm *trustedForm
|
||||
)
|
||||
for _, target := range []any{nil, nilForm, 7, &[]string{}, trustedForm{}} {
|
||||
ctx, _ := gin.CreateTestContext(httptest.NewRecorder())
|
||||
ctx.Request = httptest.NewRequest("GET", "/", nil)
|
||||
if err := InjectTrustedFields(ctx, target, nil); err == nil {
|
||||
t.Fatalf("accepted %T", target)
|
||||
}
|
||||
}
|
||||
ctx, _ := gin.CreateTestContext(httptest.NewRecorder())
|
||||
ctx.Request = httptest.NewRequest("GET", "/", nil)
|
||||
form := &trustedForm{hidden: "untouched"}
|
||||
if err := InjectTrustedFields(ctx, form, map[string]TrustedField{"hidden": func(*gin.Context) (any, error) { t.Fatal("private field read"); return nil, nil }}); err == nil {
|
||||
t.Fatal("accepted private field")
|
||||
}
|
||||
|
||||
if form.hidden != "untouched" {
|
||||
t.Fatal("private field modified")
|
||||
}
|
||||
}
|
||||