1 parent
568e516b1a
commit
7ea7b153a2
10 files changed
+595
-46
No files matched your search
@@ -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[:])}
|
||||
}
|
||||