Merge branch 'master' of https://git.zhangdeman.cn/zhangdeman/ginframework
Verify / verify (push) Canceled after 0s
Verify / verify (push) Canceled after 0s
This commit is contained in:
commit
72f80b6ca0
6 files changed
+307
-17
No files matched your search
@@ -9,6 +9,8 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"git.zhangdeman.cn/zhangdeman/ginframework/logger/storagevalue"
|
||||||
|
|
||||||
mysqlDriver "github.com/go-sql-driver/mysql"
|
mysqlDriver "github.com/go-sql-driver/mysql"
|
||||||
"go.uber.org/zap"
|
"go.uber.org/zap"
|
||||||
"go.uber.org/zap/zaptest/observer"
|
"go.uber.org/zap/zaptest/observer"
|
||||||
@@ -48,6 +50,18 @@ type sqlObservationRow struct {
|
|||||||
Name string
|
Name string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestDisabledSensitiveDetectionKeepsCredentialSQLPolicy 验证关闭敏感检测后凭据语句不再整条隐藏,config_value 仍按固定策略隐藏。
|
||||||
|
func TestDisabledSensitiveDetectionKeepsCredentialSQLPolicy(t *testing.T) {
|
||||||
|
storagevalue.SetSensitiveDetection(false)
|
||||||
|
defer storagevalue.SetSensitiveDetection(true)
|
||||||
|
if got := RedactSQL("SELECT ? AS token"); got != "SELECT ? AS token" {
|
||||||
|
t.Fatalf("credential SQL still hidden: %s", got)
|
||||||
|
}
|
||||||
|
if got := RedactSQL("UPDATE setting SET config_value='private-value'"); got != "[REDACTED SQL]" {
|
||||||
|
t.Fatalf("config_value SQL was not hidden: %s", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// TestSQLExecutionLogsOnce 验证真实 ORM 执行只输出一次插值后的完整 SQL,不重复记录模板或参数。
|
// TestSQLExecutionLogsOnce 验证真实 ORM 执行只输出一次插值后的完整 SQL,不重复记录模板或参数。
|
||||||
func TestSQLExecutionLogsOnce(t *testing.T) {
|
func TestSQLExecutionLogsOnce(t *testing.T) {
|
||||||
var (
|
var (
|
||||||
|
|||||||
@@ -31,7 +31,7 @@ go mod tidy
|
|||||||
| `diagnostic` | 标准 Context 的可信标量快照 | HTTP/Worker 入口 |
|
| `diagnostic` | 标准 Context 的可信标量快照 | HTTP/Worker 入口 |
|
||||||
| `fault` | 内部数字场景错误和原因链 | 基础设施/业务适配边界 |
|
| `fault` | 内部数字场景错误和原因链 | 基础设施/业务适配边界 |
|
||||||
| `logger` | 命名 Zap 输出、轮转、错误及 Context 诊断 | 进程启动与最后退出 |
|
| `logger` | 命名 Zap 输出、轮转、错误及 Context 诊断 | 进程启动与最后退出 |
|
||||||
| `logger/storagevalue` | 日志脱敏副本及诊断提取 | 执行观测、应用日志 |
|
| `logger/storagevalue` | 日志脱敏副本、可定制敏感内容列表、敏感检测开关及诊断提取 | 执行观测、应用日志 |
|
||||||
| `database` | MySQL/GORM 连接、探测、插件与原生会话 | 应用装配根 |
|
| `database` | MySQL/GORM 连接、探测、插件与原生会话 | 应用装配根 |
|
||||||
| `database/query` | 可选 GORM 条件、表级泛型 DAO 与列表目标 | 借用调用方原生会话,不建池 |
|
| `database/query` | 可选 GORM 条件、表级泛型 DAO 与列表目标 | 借用调用方原生会话,不建池 |
|
||||||
| `database/dberror` | 可选唯一键冲突类型识别 | MySQL/GORM;CGO 时支持 SQLite 驱动 |
|
| `database/dberror` | 可选唯一键冲突类型识别 | MySQL/GORM;CGO 时支持 SQLite 驱动 |
|
||||||
@@ -316,6 +316,10 @@ Name 和 Path 必填;MaxAge 单位秒,非正值使用三天。文件轮转
|
|||||||
|
|
||||||
结构化附加数据使用 `logger.Fields(data)` 或 `storagevalue.Safe(data)` 生成脱敏副本;不会修改真实对象。不要把未经筛选的正文、URL、error.Error() 拼入英文 msg。
|
结构化附加数据使用 `logger.Fields(data)` 或 `storagevalue.Safe(data)` 生成脱敏副本;不会修改真实对象。不要把未经筛选的正文、URL、error.Error() 拼入英文 msg。
|
||||||
|
|
||||||
|
敏感内容片段默认由 `storagevalue.DefaultSensitiveList()` 提供,`storagevalue.Sensitive(key)` 按该默认列表判定。应用需要自定义敏感内容时用 `storagevalue.NewSensitiveList(parts)` 构造独立列表,用 `storagevalue.DefaultSensitiveList().Extend(parts...)` 在默认列表之上扩展,再用 `storagevalue.SafeWith(value, list)` 生成按该列表脱敏的副本。片段按小写并把连字符视为下划线后做包含匹配;自定义列表整体替换默认列表,扩展列表保留默认片段。
|
||||||
|
|
||||||
|
敏感检测默认开启,应用可在受控排障环境用 `storagevalue.SetSensitiveDetection(false)` 手动关闭,用 `storagevalue.SensitiveDetectionEnabled()` 查询当前状态。关闭后库内按名称自动识别凭据字段的隐藏全部失效:`logger.Fields` 与 `storagevalue.Safe` 的副本保留原始值,访问日志的请求/响应头过滤与正文副本保留原值,SQL 参数副本和凭据语句整条隐藏不再生效,Redis 命令参数与结果副本保留原值。以下固定策略不受开关影响:访问日志固定忽略的凭据头名单与应用的 `RedactKeys`、`storagevalue.SafeWith(value, list)` 显式传入的敏感列表、SQL 的 `config_value` 字段、Redis 的认证管理命令。开关只改变副本内容,不修改请求数据、执行参数、返回对象或业务 DTO。关闭期间日志可能包含凭据原文,仅在受控环境短时使用,结束后恢复开启。
|
||||||
|
|
||||||
### 6.3 Context 与内部错误
|
### 6.3 Context 与内部错误
|
||||||
|
|
||||||
后台入口用 `diagnostic.With(ctx, diagnostic.Snapshot{...})` 建立可信标量快照;无请求来源时不要伪造 request_id。`diagnostic.From(ctx)` 返回副本。普通业务能力使用标准 context.Context,避免为了日志构造伪 Gin 请求。请求绑定、校验、可信注入、连接启动错误和出站错误均在接收处使用该上下文记录;出站 Response 只保存可信标量诊断副本,让后续 DecodeJSON 的错误仍可关联原请求,不持有 HTTP 请求或可变 Context。
|
后台入口用 `diagnostic.With(ctx, diagnostic.Snapshot{...})` 建立可信标量快照;无请求来源时不要伪造 request_id。`diagnostic.From(ctx)` 返回副本。普通业务能力使用标准 context.Context,避免为了日志构造伪 Gin 请求。请求绑定、校验、可信注入、连接启动错误和出站错误均在接收处使用该上下文记录;出站 Response 只保存可信标量诊断副本,让后续 DecodeJSON 的错误仍可关联原请求,不持有 HTTP 请求或可变 Context。
|
||||||
@@ -467,7 +471,7 @@ make verify 包含 docs-check、格式、架构依赖、vet、build、test 和
|
|||||||
|
|
||||||
`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。各阶段策略独立,可显式覆盖。
|
`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 仍仅记录协议元数据;安装该可选中间件时按需关闭前者避免重复完成流水。
|
敏感请求头不可通过允许名单重新启用。数据复用 storagevalue.Safe,支持结构体、集合和 JSON 字符串副本;额外敏感键忽略大小写并在副本中替换。未配置或非正数阈值为 4 KiB,超过时仅输出 truncated、original_bytes、sha256,摘要基于脱敏后数据。阈值限制日志输出,不是读取/内存上限;应用须限制数据规模,不传入不可信且无界的对象。Record 含进入/完成标记、时间、单调耗时、状态、头、查询首值和正文;不含原始 URL 查询串。同步 Emit 可附加可信诊断和业务字段,框架不关闭应用日志资源。原生 Server 的 Options.AccessLogger 仍仅记录协议元数据;安装该可选中间件时按需关闭前者避免重复完成流水。关闭 storagevalue 的敏感检测后,按名称识别的敏感头与正文字段不再被过滤,固定忽略的凭据头和应用的 RedactKeys 仍然生效。
|
||||||
|
|
||||||
`http/recovery.New(recovery.Options{Report: ..., Respond: ...})` 捕获当前请求协程 panic。Incident 仅保留动态类型和一次 debug.Stack,不携带原始 panic 值;Report 为 nil 使用框架 default 安全错误日志(独立场景码 901001,Server 仍保留既有 900409),Respond 为 nil 使用通用 JSON 500。Report/Respond 为同步应用回调,应用负责并发安全和诊断脱敏。先报告并 Abort,再仅在响应未提交时调用 Respond;已写出响应或 SSE Flush 后不会追加 JSON 或更改状态。普通 error 不进入恢复,业务创建的子协程须自行管理。Server 已通过该实现保留原有错误映射;应用嵌套安装时由最近的恢复边界处理,不重复记录同一 panic。无后台任务和待关闭资源。
|
`http/recovery.New(recovery.Options{Report: ..., Respond: ...})` 捕获当前请求协程 panic。Incident 仅保留动态类型和一次 debug.Stack,不携带原始 panic 值;Report 为 nil 使用框架 default 安全错误日志(独立场景码 901001,Server 仍保留既有 900409),Respond 为 nil 使用通用 JSON 500。Report/Respond 为同步应用回调,应用负责并发安全和诊断脱敏。先报告并 Abort,再仅在响应未提交时调用 Respond;已写出响应或 SSE Flush 后不会追加 JSON 或更改状态。普通 error 不进入恢复,业务创建的子协程须自行管理。Server 已通过该实现保留原有错误映射;应用嵌套安装时由最近的恢复边界处理,不重复记录同一 panic。无后台任务和待关闭资源。
|
||||||
|
|
||||||
|
|||||||
@@ -8,6 +8,8 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"git.zhangdeman.cn/zhangdeman/ginframework/logger/storagevalue"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -90,3 +92,33 @@ func TestDefaultPoliciesAndDisabledCollector(t *testing.T) {
|
|||||||
engine.GET("/api", func(ctx *gin.Context) { ctx.Status(204) })
|
engine.GET("/api", func(ctx *gin.Context) { ctx.Status(204) })
|
||||||
engine.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "/api", nil))
|
engine.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "/api", nil))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestDisabledSensitiveDetectionKeepsFixedPolicies 验证关闭敏感检测后正文保留原值,固定忽略的凭据头仍然隐藏。
|
||||||
|
func TestDisabledSensitiveDetectionKeepsFixedPolicies(t *testing.T) {
|
||||||
|
storagevalue.SetSensitiveDetection(false)
|
||||||
|
defer storagevalue.SetSensitiveDetection(true)
|
||||||
|
records := []Record{}
|
||||||
|
engine := gin.New()
|
||||||
|
engine.Use(New(Config{}, Options{
|
||||||
|
RequestBody: func(*gin.Context) any { return map[string]any{"password": "private-password"} },
|
||||||
|
Emit: func(_ *gin.Context, r Record) { records = append(records, r) },
|
||||||
|
}))
|
||||||
|
engine.POST("/api", func(ctx *gin.Context) { ctx.Status(204) })
|
||||||
|
req := httptest.NewRequest("POST", "/api", strings.NewReader("{}"))
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
req.Header.Set("Authorization", "private-header")
|
||||||
|
engine.ServeHTTP(httptest.NewRecorder(), req)
|
||||||
|
if len(records) != 1 {
|
||||||
|
t.Fatalf("records=%+v", records)
|
||||||
|
}
|
||||||
|
if records[0].Header.Get("Authorization") != "" {
|
||||||
|
t.Fatal("fixed credential header policy was disabled")
|
||||||
|
}
|
||||||
|
body, err := json.Marshal(records[0].Body)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !strings.Contains(string(body), "private-password") {
|
||||||
|
t.Fatal("disabled detection still hid the body field")
|
||||||
|
}
|
||||||
|
}
|
||||||
+108
-15
@@ -7,35 +7,128 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"reflect"
|
"reflect"
|
||||||
"strings"
|
"strings"
|
||||||
|
"sync/atomic"
|
||||||
|
|
||||||
"git.zhangdeman.cn/zhangdeman/ginframework/diagnostic"
|
"git.zhangdeman.cn/zhangdeman/ginframework/diagnostic"
|
||||||
"go.uber.org/zap"
|
"go.uber.org/zap"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Sensitive 检查字段或键是否具有凭据语义。
|
var (
|
||||||
|
// defaultSensitiveParts 是全局默认的敏感内容片段列表,键名包含其中任一片段即视为敏感。
|
||||||
|
defaultSensitiveParts = SensitiveList{
|
||||||
|
"password", "passwd", "salt", "secret", "token", "credential",
|
||||||
|
"authorization", "cookie", "private_key", "privatekey",
|
||||||
|
"api_key", "apikey", "access_key", "accesskey",
|
||||||
|
"card_key", "cardkey", "verification_code", "verificationcode",
|
||||||
|
}
|
||||||
|
|
||||||
|
// sensitiveDetection 控制日志副本是否按名称自动识别凭据字段,缺省开启。
|
||||||
|
sensitiveDetection atomic.Bool
|
||||||
|
)
|
||||||
|
|
||||||
|
// init 设置敏感检测的缺省状态为开启。
|
||||||
|
func init() {
|
||||||
|
sensitiveDetection.Store(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
// SensitiveList 保存敏感内容片段列表,按片段包含关系判定键名是否具有凭据语义。
|
||||||
|
type SensitiveList []string
|
||||||
|
|
||||||
|
// DefaultSensitiveList 返回全局默认的敏感内容片段列表副本。
|
||||||
|
// 返回:默认片段副本,调用方修改不影响库内默认行为。
|
||||||
|
func DefaultSensitiveList() SensitiveList {
|
||||||
|
return append(SensitiveList(nil), defaultSensitiveParts...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewSensitiveList 返回使用指定片段构造的敏感列表,片段为空时返回默认列表副本。
|
||||||
|
// 入参:parts 为敏感内容片段,与键名按同一规则归一后参与匹配。
|
||||||
|
// 返回:独立片段列表,调用方修改不影响库内默认行为。
|
||||||
|
func NewSensitiveList(parts []string) SensitiveList {
|
||||||
|
if len(parts) == 0 {
|
||||||
|
return DefaultSensitiveList()
|
||||||
|
}
|
||||||
|
return append(SensitiveList(nil), parts...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Extend 返回在当前列表之上追加片段后的新列表,不修改当前列表。
|
||||||
|
// 入参:parts 为追加的敏感内容片段。
|
||||||
|
// 返回:追加后的新列表。
|
||||||
|
func (l SensitiveList) Extend(parts ...string) SensitiveList {
|
||||||
|
extended := make(SensitiveList, 0, len(l)+len(parts))
|
||||||
|
extended = append(extended, l...)
|
||||||
|
extended = append(extended, parts...)
|
||||||
|
return extended
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sensitive 判断键名是否命中列表中的任一敏感片段。
|
||||||
// 入参:key 为日志字段名、SQL 或 Redis 键的描述。
|
// 入参:key 为日志字段名、SQL 或 Redis 键的描述。
|
||||||
// 返回:需要隐藏原始值时返回 true。
|
// 返回:需要隐藏原始值时返回 true。
|
||||||
func Sensitive(key string) bool {
|
func (l SensitiveList) Sensitive(key string) bool {
|
||||||
var (
|
var (
|
||||||
lower = strings.ToLower(strings.ReplaceAll(key, "-", "_"))
|
lower = normalizeSensitivePart(key)
|
||||||
)
|
)
|
||||||
for _, part := range []string{"password", "passwd", "salt", "secret", "token", "credential", "authorization", "cookie", "private_key", "privatekey", "api_key", "apikey", "access_key", "accesskey", "card_key", "cardkey", "verification_code", "verificationcode"} {
|
for _, part := range l {
|
||||||
if strings.Contains(lower, part) {
|
if part == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if strings.Contains(lower, normalizeSensitivePart(part)) {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
// Safe 生成可记录的结构副本,递归解析 JSON 字符串并隐藏凭据字段。
|
// SetSensitiveDetection 设置日志副本的敏感检测开关,缺省开启。
|
||||||
|
// 入参:enabled 为 true 时按名称自动识别凭据字段,为 false 时只生成副本而不再隐藏凭据字段。
|
||||||
|
// 副作用:影响同一进程内后续的包级 Sensitive 与 Safe 调用;显式传入的敏感列表和各组件固定隐藏策略不受影响。
|
||||||
|
func SetSensitiveDetection(enabled bool) {
|
||||||
|
sensitiveDetection.Store(enabled)
|
||||||
|
}
|
||||||
|
|
||||||
|
// SensitiveDetectionEnabled 返回当前敏感检测开关状态。
|
||||||
|
// 返回:按名称自动识别凭据字段时返回 true。
|
||||||
|
func SensitiveDetectionEnabled() bool {
|
||||||
|
return sensitiveDetection.Load()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sensitive 检查字段或键是否具有凭据语义,使用全局默认敏感内容列表。
|
||||||
|
// 入参:key 为日志字段名、SQL 或 Redis 键的描述。
|
||||||
|
// 返回:需要隐藏原始值时返回 true;敏感检测关闭时恒返回 false。
|
||||||
|
func Sensitive(key string) bool {
|
||||||
|
if !sensitiveDetection.Load() {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return defaultSensitiveParts.Sensitive(key)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Safe 生成可记录的结构副本,递归解析 JSON 字符串并按默认列表隐藏凭据字段。
|
||||||
// 入参:value 为待记录的执行参数或返回值。
|
// 入参:value 为待记录的执行参数或返回值。
|
||||||
// 返回:与真实对象分离的日志值,无法安全表示的类型只保留类型名。
|
// 返回:与真实对象分离的日志值,无法安全表示的类型只保留类型名。
|
||||||
func Safe(value any) any { return safe(value, 0) }
|
// 隐式逻辑:敏感检测关闭时不隐藏凭据字段,仍生成与真实对象分离的副本。
|
||||||
|
func Safe(value any) any {
|
||||||
|
if !sensitiveDetection.Load() {
|
||||||
|
return safe(value, 0, nil)
|
||||||
|
}
|
||||||
|
return safe(value, 0, defaultSensitiveParts)
|
||||||
|
}
|
||||||
|
|
||||||
|
// SafeWith 使用指定敏感列表生成可记录的结构副本,递归解析 JSON 字符串并隐藏凭据字段。
|
||||||
|
// 入参:value 为待记录的执行参数或返回值,list 为参与脱敏的敏感内容片段列表。
|
||||||
|
// 返回:与真实对象分离的日志值,无法安全表示的类型只保留类型名。
|
||||||
|
// 隐式逻辑:显式列表始终生效,不受全局敏感检测开关影响。
|
||||||
|
func SafeWith(value any, list SensitiveList) any { return safe(value, 0, list) }
|
||||||
|
|
||||||
|
// normalizeSensitivePart 统一键名与敏感片段的比较形式,转小写并把连字符替换为下划线。
|
||||||
|
// 入参:value 为键名或敏感片段。
|
||||||
|
// 返回:归一后的比较文本。
|
||||||
|
func normalizeSensitivePart(value string) string {
|
||||||
|
return strings.ToLower(strings.ReplaceAll(value, "-", "_"))
|
||||||
|
}
|
||||||
|
|
||||||
// safe 限制递归深度,避免日志遍历循环对象。
|
// safe 限制递归深度,避免日志遍历循环对象。
|
||||||
// 入参:value 为当前值,depth 为嵌套层数。
|
// 入参:value 为当前值,depth 为嵌套层数,list 为参与脱敏的敏感内容片段列表。
|
||||||
// 返回:不持有可变业务对象的日志副本。
|
// 返回:不持有可变业务对象的日志副本。
|
||||||
func safe(value any, depth int) any {
|
func safe(value any, depth int, list SensitiveList) any {
|
||||||
var (
|
var (
|
||||||
target any
|
target any
|
||||||
data []byte
|
data []byte
|
||||||
@@ -57,22 +150,22 @@ func safe(value any, depth int) any {
|
|||||||
if err = decoder.Decode(&target); err == nil {
|
if err = decoder.Decode(&target); err == nil {
|
||||||
switch target.(type) {
|
switch target.(type) {
|
||||||
case map[string]any, []any:
|
case map[string]any, []any:
|
||||||
return safe(target, depth+1)
|
return safe(target, depth+1, list)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return typed
|
return typed
|
||||||
case []byte:
|
case []byte:
|
||||||
return safe(string(typed), depth+1)
|
return safe(string(typed), depth+1, list)
|
||||||
case map[string]any:
|
case map[string]any:
|
||||||
var (
|
var (
|
||||||
result = make(map[string]any, len(typed))
|
result = make(map[string]any, len(typed))
|
||||||
)
|
)
|
||||||
for key, item := range typed {
|
for key, item := range typed {
|
||||||
if Sensitive(key) {
|
if list.Sensitive(key) {
|
||||||
result[key] = "[REDACTED]"
|
result[key] = "[REDACTED]"
|
||||||
} else {
|
} else {
|
||||||
result[key] = safe(item, depth+1)
|
result[key] = safe(item, depth+1, list)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return result
|
return result
|
||||||
@@ -81,7 +174,7 @@ func safe(value any, depth int) any {
|
|||||||
result = make([]any, len(typed))
|
result = make([]any, len(typed))
|
||||||
)
|
)
|
||||||
for index, item := range typed {
|
for index, item := range typed {
|
||||||
result[index] = safe(item, depth+1)
|
result[index] = safe(item, depth+1, list)
|
||||||
}
|
}
|
||||||
return result
|
return result
|
||||||
case bool, int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, float32, float64, json.Number:
|
case bool, int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, float32, float64, json.Number:
|
||||||
@@ -98,7 +191,7 @@ func safe(value any, depth int) any {
|
|||||||
if err = decoder.Decode(&target); err != nil {
|
if err = decoder.Decode(&target); err != nil {
|
||||||
return reflect.TypeOf(value).String()
|
return reflect.TypeOf(value).String()
|
||||||
}
|
}
|
||||||
return safe(target, depth+1)
|
return safe(target, depth+1, list)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Diagnostics 提取标准上下文中的可信诊断快照,不记录任意上下文值。
|
// Diagnostics 提取标准上下文中的可信诊断快照,不记录任意上下文值。
|
||||||
|
|||||||
@@ -31,3 +31,116 @@ func TestCredentialCopiesPreserveOriginalAndNumbers(t *testing.T) {
|
|||||||
t.Fatal("redaction modified execution data")
|
t.Fatal("redaction modified execution data")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestDefaultSensitiveListMatchesCredentialKeys 验证默认列表覆盖凭据字段名并归一连字符形式。
|
||||||
|
func TestDefaultSensitiveListMatchesCredentialKeys(t *testing.T) {
|
||||||
|
for _, key := range []string{"password", "User-Password", "apiKey", "api_key", "verification_code", "private-key"} {
|
||||||
|
if !Sensitive(key) {
|
||||||
|
t.Fatalf("default list missed credential key %s", key)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if Sensitive("user_name") {
|
||||||
|
t.Fatal("default list flagged a plain field")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestNewSensitiveListReplacesDefault 验证自定义列表只按传入片段判定,不继承默认列表。
|
||||||
|
func TestNewSensitiveListReplacesDefault(t *testing.T) {
|
||||||
|
var (
|
||||||
|
list = NewSensitiveList([]string{"employee_no"})
|
||||||
|
)
|
||||||
|
if !list.Sensitive("Employee-No") {
|
||||||
|
t.Fatal("custom list missed its own part")
|
||||||
|
}
|
||||||
|
if list.Sensitive("password") {
|
||||||
|
t.Fatal("custom list inherited the default parts")
|
||||||
|
}
|
||||||
|
if NewSensitiveList(nil).Sensitive("password") != Sensitive("password") {
|
||||||
|
t.Fatal("empty custom list differs from the default list")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestExtendAddsPartsOnTopOfCurrentList 验证扩展在当前列表之上追加片段且不修改原列表。
|
||||||
|
func TestExtendAddsPartsOnTopOfCurrentList(t *testing.T) {
|
||||||
|
var (
|
||||||
|
base = DefaultSensitiveList()
|
||||||
|
extended = base.Extend("employee_no")
|
||||||
|
)
|
||||||
|
if !extended.Sensitive("employee_no") {
|
||||||
|
t.Fatal("extended list missed the appended part")
|
||||||
|
}
|
||||||
|
if !extended.Sensitive("password") {
|
||||||
|
t.Fatal("extended list lost the default parts")
|
||||||
|
}
|
||||||
|
if base.Sensitive("employee_no") {
|
||||||
|
t.Fatal("extend modified the original list")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestSafeWithAppliesCustomList 验证自定义列表参与结构副本脱敏且不改写原始数据。
|
||||||
|
func TestSafeWithAppliesCustomList(t *testing.T) {
|
||||||
|
var (
|
||||||
|
original = map[string]any{"employee_no": "private-no", "password": "private-password"}
|
||||||
|
list = NewSensitiveList([]string{"employee_no"})
|
||||||
|
result = SafeWith(original, list)
|
||||||
|
body, err = json.Marshal(result)
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !strings.Contains(string(body), "[REDACTED]") {
|
||||||
|
t.Fatal("custom list did not redact the field")
|
||||||
|
}
|
||||||
|
if strings.Contains(string(body), "private-no") {
|
||||||
|
t.Fatal("custom sensitive value appeared in log copy")
|
||||||
|
}
|
||||||
|
if !strings.Contains(string(body), "private-password") {
|
||||||
|
t.Fatal("replaced list still redacted the default sensitive key")
|
||||||
|
}
|
||||||
|
if original["employee_no"] != "private-no" {
|
||||||
|
t.Fatal("redaction modified execution data")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestSensitiveDetectionSwitch 验证敏感检测缺省开启,可手动关闭后不再按名称隐藏凭据字段,显式列表仍然生效。
|
||||||
|
func TestSensitiveDetectionSwitch(t *testing.T) {
|
||||||
|
var (
|
||||||
|
original = map[string]any{"password": "private-password"}
|
||||||
|
)
|
||||||
|
defer SetSensitiveDetection(true)
|
||||||
|
if !SensitiveDetectionEnabled() {
|
||||||
|
t.Fatal("sensitive detection must be enabled by default")
|
||||||
|
}
|
||||||
|
if !Sensitive("password") {
|
||||||
|
t.Fatal("default detection missed credential key")
|
||||||
|
}
|
||||||
|
if body, _ := json.Marshal(Safe(original)); !strings.Contains(string(body), "[REDACTED]") {
|
||||||
|
t.Fatal("default detection did not hide credential field")
|
||||||
|
}
|
||||||
|
SetSensitiveDetection(false)
|
||||||
|
if SensitiveDetectionEnabled() {
|
||||||
|
t.Fatal("switch state was not closed")
|
||||||
|
}
|
||||||
|
if Sensitive("password") {
|
||||||
|
t.Fatal("closed detection still flagged credential key")
|
||||||
|
}
|
||||||
|
var (
|
||||||
|
body, err = json.Marshal(Safe(original))
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !strings.Contains(string(body), "private-password") {
|
||||||
|
t.Fatal("closed detection still hid credential field")
|
||||||
|
}
|
||||||
|
if original["password"] != "private-password" {
|
||||||
|
t.Fatal("closed detection modified execution data")
|
||||||
|
}
|
||||||
|
if explicit, err := json.Marshal(SafeWith(original, DefaultSensitiveList())); err != nil || !strings.Contains(string(explicit), "[REDACTED]") {
|
||||||
|
t.Fatal("explicit sensitive list must stay effective")
|
||||||
|
}
|
||||||
|
SetSensitiveDetection(true)
|
||||||
|
if !Sensitive("password") {
|
||||||
|
t.Fatal("re-enabled detection did not resume")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -8,6 +8,7 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"git.zhangdeman.cn/zhangdeman/ginframework/internal/testutil/redisserver"
|
"git.zhangdeman.cn/zhangdeman/ginframework/internal/testutil/redisserver"
|
||||||
|
"git.zhangdeman.cn/zhangdeman/ginframework/logger/storagevalue"
|
||||||
|
|
||||||
"github.com/redis/go-redis/v9"
|
"github.com/redis/go-redis/v9"
|
||||||
"go.uber.org/zap"
|
"go.uber.org/zap"
|
||||||
@@ -75,3 +76,36 @@ func TestHookObservesReturnedError(t *testing.T) {
|
|||||||
t.Fatalf("hook altered command or observed wrong result: %v", logs.All())
|
t.Fatalf("hook altered command or observed wrong result: %v", logs.All())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestDisabledSensitiveDetectionKeepsFixedHiddenCommands 验证关闭敏感检测后普通命令保留原始参数,认证管理命令仍然整组隐藏。
|
||||||
|
func TestDisabledSensitiveDetectionKeepsFixedHiddenCommands(t *testing.T) {
|
||||||
|
storagevalue.SetSensitiveDetection(false)
|
||||||
|
defer storagevalue.SetSensitiveDetection(true)
|
||||||
|
var (
|
||||||
|
core, logs = observer.New(zap.InfoLevel)
|
||||||
|
hook = New(zap.New(core), "cache")
|
||||||
|
process = hook.ProcessHook(func(context.Context, redis.Cmder) error { return nil })
|
||||||
|
)
|
||||||
|
if err := process(context.Background(), redis.NewStringCmd(context.Background(), "set", "user:token", "private-value")); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := process(context.Background(), redis.NewStringCmd(context.Background(), "auth", "private-password")); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var (
|
||||||
|
entries = logs.All()
|
||||||
|
)
|
||||||
|
if len(entries) != 2 {
|
||||||
|
t.Fatalf("entries=%d, want 2", len(entries))
|
||||||
|
}
|
||||||
|
body, err := json.Marshal(entries[0].ContextMap())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !strings.Contains(string(body), "private-value") {
|
||||||
|
t.Fatal("disabled detection still hid ordinary command arguments")
|
||||||
|
}
|
||||||
|
if entries[1].ContextMap()["args"] != "[REDACTED]" || entries[1].ContextMap()["value"] != "[REDACTED]" {
|
||||||
|
t.Fatal("fixed hidden command policy was disabled")
|
||||||
|
}
|
||||||
|
}
|
||||||