feat(middleware): enhance logger to sanitize new and old password fields

Updated the logger to include regex patterns for sanitizing "new_password" and "old_password" fields in JSON logs. Added a corresponding test case to verify the sanitization functionality.
This commit is contained in:
wizardchen
2026-07-13 20:09:43 +08:00
committed by lyingbug
parent 8ec65941a5
commit a6c85dad28
2 changed files with 8 additions and 3 deletions
+3 -3
View File
@@ -42,9 +42,9 @@ func (r loggerResponseBodyWriter) Write(b []byte) (int, error) {
// sensitiveFieldRegex 匹配 JSON 中的敏感字段(不区分大小写,兼容 snake_case / camelCase / PascalCase)。
// $1 捕获原始字段名(包括两侧引号),保持日志中的字段名不变,仅将值替换为 "***"。
var sensitiveFieldRegex = regexp.MustCompile(
`(?i)("(?:password|passwd|token|access[_-]?token|refresh[_-]?token|id[_-]?token|` +
`authorization|auth[_-]?token|api[_-]?key|api[_-]?secret|secret[_-]?key|` +
`client[_-]?secret|private[_-]?key|secret)")\s*:\s*"[^"]*"`,
`(?i)("(?:new[_-]?password|old[_-]?password|password|passwd|token|access[_-]?token|` +
`refresh[_-]?token|id[_-]?token|authorization|auth[_-]?token|api[_-]?key|` +
`api[_-]?secret|secret[_-]?key|client[_-]?secret|private[_-]?key|secret)")\s*:\s*"[^"]*"`,
)
// sanitizeBody 清理敏感信息
+5
View File
@@ -38,6 +38,11 @@ func TestSanitizeBody(t *testing.T) {
in: `{"password":"p","token":"t"}`,
want: `{"password":"***","token":"***"}`,
},
{
name: "snake_case new_password and old_password",
in: `{"email":"alice@example.com","new_password":"FreshPass9","old_password":"OldPass9"}`,
want: `{"email":"alice@example.com","new_password":"***","old_password":"***"}`,
},
{
name: "extra whitespace around colon",
in: `{"apiKey" : "leak"}`,