-
Notifications
You must be signed in to change notification settings - Fork 11.1k
fix: 慢查询/错误 SQL 日志参数化 #6493
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Calcium-Ion
merged 4 commits into
QuantumNous:main
from
feitianbubu:fix/parameterized-sql-log
Jul 27, 2026
Merged
fix: 慢查询/错误 SQL 日志参数化 #6493
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
f7fa82a
fix: parameterize slow/error SQL logs to avoid leaking credentials
feitianbubu dbb91cc
fix: validate SQL_SLOW_THRESHOLD_MS range
feitianbubu a419779
fix: sanitize database driver error messages in SQL logs
feitianbubu b80df71
refactor: sanitize at gorm log writer seam to keep caller attribution
feitianbubu File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,86 @@ | ||
| package model | ||
|
|
||
| import ( | ||
| "errors" | ||
| "fmt" | ||
| "io" | ||
| "log" | ||
| "os" | ||
| "time" | ||
|
|
||
| "github.com/ClickHouse/clickhouse-go/v2/lib/proto" | ||
| "github.com/QuantumNous/new-api/common" | ||
| sqlitedriver "github.com/glebarez/go-sqlite" | ||
| "github.com/go-sql-driver/mysql" | ||
| "github.com/jackc/pgx/v5/pgconn" | ||
| "gorm.io/gorm" | ||
| "gorm.io/gorm/logger" | ||
| ) | ||
|
|
||
| const ( | ||
| defaultSlowThresholdMs = 200 | ||
| maxSlowThresholdMs = 60 * 60 * 1000 | ||
| ) | ||
|
|
||
| func newGormConfig(prepareStmt bool) *gorm.Config { | ||
| return &gorm.Config{ | ||
| PrepareStmt: prepareStmt, | ||
| Logger: newGormLogger(os.Stdout), | ||
| } | ||
| } | ||
|
|
||
| func newGormLogger(w io.Writer) logger.Interface { | ||
| slowThresholdMs := common.GetEnvOrDefault("SQL_SLOW_THRESHOLD_MS", defaultSlowThresholdMs) | ||
| if slowThresholdMs < 0 || slowThresholdMs > maxSlowThresholdMs { | ||
| common.SysError(fmt.Sprintf("invalid SQL_SLOW_THRESHOLD_MS %d (allowed 0-%d, 0 disables slow query log), using default %d", slowThresholdMs, maxSlowThresholdMs, defaultSlowThresholdMs)) | ||
| slowThresholdMs = defaultSlowThresholdMs | ||
| } | ||
| // 在 Writer 层脱敏而非包装 logger.Interface:后者会让 gorm 的 FileWithLineNum | ||
| // 把所有 SQL 日志的调用点归因到包装层自身,且需转发 ParamsFilter 类型断言。 | ||
| return logger.New(&sanitizedLogWriter{delegate: log.New(w, "\r\n", log.LstdFlags)}, logger.Config{ | ||
| SlowThreshold: time.Duration(slowThresholdMs) * time.Millisecond, | ||
| LogLevel: logger.Warn, | ||
| IgnoreRecordNotFoundError: true, | ||
| ParameterizedQueries: !common.DebugEnabled, | ||
| Colorful: true, | ||
| }) | ||
| } | ||
|
|
||
| // ParameterizedQueries 只过滤 SQL 字符串,驱动错误消息(如 MySQL 1062)同样会 | ||
| // 内联数据值,在这里收敛为错误码;DEBUG=true 保留原文。 | ||
| type sanitizedLogWriter struct { | ||
| delegate *log.Logger | ||
| } | ||
|
|
||
| func (s *sanitizedLogWriter) Printf(format string, args ...interface{}) { | ||
| if !common.DebugEnabled { | ||
| for i, arg := range args { | ||
| if err, ok := arg.(error); ok { | ||
| args[i] = sanitizeDBError(err) | ||
| } | ||
| } | ||
| } | ||
| s.delegate.Printf(format, args...) | ||
| } | ||
|
|
||
| // 只收敛数据库服务端生成的驱动错误(消息可能内联数据值);网络/上下文等 | ||
| // 其它错误不含查询数据,原样保留以便排障。 | ||
| func sanitizeDBError(err error) error { | ||
| var mysqlErr *mysql.MySQLError | ||
| if errors.As(err, &mysqlErr) { | ||
| return fmt.Errorf("mysql error %d", mysqlErr.Number) | ||
| } | ||
| var pgErr *pgconn.PgError | ||
| if errors.As(err, &pgErr) { | ||
| return fmt.Errorf("postgres error SQLSTATE %s", pgErr.Code) | ||
| } | ||
| var chErr *proto.Exception | ||
| if errors.As(err, &chErr) { | ||
| return fmt.Errorf("clickhouse error %d", chErr.Code) | ||
| } | ||
| var sqliteErr *sqlitedriver.Error | ||
| if errors.As(err, &sqliteErr) { | ||
| return fmt.Errorf("sqlite error %d", sqliteErr.Code()) | ||
| } | ||
| return err | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,102 @@ | ||
| package model | ||
|
|
||
| import ( | ||
| "bytes" | ||
| "fmt" | ||
| "testing" | ||
|
|
||
| "github.com/ClickHouse/clickhouse-go/v2/lib/proto" | ||
| "github.com/QuantumNous/new-api/common" | ||
| "github.com/glebarez/sqlite" | ||
| "github.com/go-sql-driver/mysql" | ||
| "github.com/jackc/pgx/v5/pgconn" | ||
| "github.com/stretchr/testify/assert" | ||
| "github.com/stretchr/testify/require" | ||
| "gorm.io/gorm" | ||
| ) | ||
|
|
||
| // 保护契约:数据库驱动错误消息可能内联数据值,非 DEBUG 下日志只保留错误码。 | ||
| func TestSanitizeDBErrorStripsDriverMessage(t *testing.T) { | ||
| tests := []struct { | ||
| name string | ||
| err error | ||
| want string | ||
| leaked string | ||
| }{ | ||
| { | ||
| name: "mysql duplicate entry", | ||
| err: &mysql.MySQLError{Number: 1062, Message: "Duplicate entry 'secret-value' for key 'users.idx'"}, | ||
| want: "mysql error 1062", | ||
| leaked: "secret-value", | ||
| }, | ||
| { | ||
| name: "postgres unique violation", | ||
| err: &pgconn.PgError{Code: "23505", Message: "duplicate key value", Detail: "Key (k)=(secret-value) already exists."}, | ||
| want: "postgres error SQLSTATE 23505", | ||
| leaked: "secret-value", | ||
| }, | ||
| { | ||
| name: "clickhouse exception", | ||
| err: &proto.Exception{Code: 241, Message: "Memory limit exceeded while processing 'secret-value'"}, | ||
| want: "clickhouse error 241", | ||
| leaked: "secret-value", | ||
| }, | ||
| { | ||
| name: "wrapped driver error", | ||
| err: fmt.Errorf("exec failed: %w", &mysql.MySQLError{Number: 1064, Message: "syntax error near 'secret-value'"}), | ||
| want: "mysql error 1064", | ||
| leaked: "secret-value", | ||
| }, | ||
| } | ||
| for _, tc := range tests { | ||
| t.Run(tc.name, func(t *testing.T) { | ||
| got := sanitizeDBError(tc.err) | ||
| require.Error(t, got) | ||
| assert.Equal(t, tc.want, got.Error()) | ||
| assert.NotContains(t, got.Error(), tc.leaked) | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| func TestSanitizeDBErrorSQLiteDriver(t *testing.T) { | ||
| db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{}) | ||
| require.NoError(t, err) | ||
| execErr := db.Exec("INSERT INTO missing_table (k) VALUES (?)", "secret-value").Error | ||
| require.Error(t, execErr) | ||
|
|
||
| got := sanitizeDBError(execErr) | ||
| assert.Regexp(t, `^sqlite error \d+$`, got.Error()) | ||
| assert.NotContains(t, got.Error(), "secret-value") | ||
| } | ||
|
|
||
| func TestSanitizeDBErrorKeepsNonDriverErrors(t *testing.T) { | ||
| err := fmt.Errorf("dial tcp 127.0.0.1:3306: connect: connection refused") | ||
| assert.Equal(t, err, sanitizeDBError(err)) | ||
| } | ||
|
|
||
| // 保护契约:经 gorm 真实链路,错误日志同时满足 SQL 参数化、驱动错误脱敏、 | ||
| // 调用点归因到业务代码;DEBUG=true 恢复参数值与错误原文。 | ||
| func TestGormLoggerEndToEndSanitizedOutput(t *testing.T) { | ||
| previousDebug := common.DebugEnabled | ||
| t.Cleanup(func() { common.DebugEnabled = previousDebug }) | ||
|
|
||
| execQuery := func() string { | ||
| var buf bytes.Buffer | ||
| db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{Logger: newGormLogger(&buf)}) | ||
| require.NoError(t, err) | ||
| db.Exec("SELECT * FROM missing_table WHERE k = ?", "secret-value") | ||
| return buf.String() | ||
| } | ||
|
|
||
| common.DebugEnabled = false | ||
| out := execQuery() | ||
| assert.Contains(t, out, "k = ?") | ||
| assert.NotContains(t, out, "secret-value") | ||
| assert.Contains(t, out, "sqlite error") | ||
| assert.Contains(t, out, "gorm_logger_test.go") | ||
|
|
||
| common.DebugEnabled = true | ||
| debugOut := execQuery() | ||
| assert.Contains(t, debugOut, "secret-value") | ||
| assert.Contains(t, debugOut, "no such table") | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.