fix(config): mask passwords in unparseable DSN URLs

Redact only masked URL userinfo when url.Parse succeeded. A password
with an unencoded # / ? or % fails to parse, so the startup config
snapshot and the ping error logged it in full.
This commit is contained in:
chuenchen309
2026-11-27 04:14:25 +08:00
parent 3cb06383fd
commit ec8c6a16cf
2 changed files with 16 additions and 2 deletions
+11 -2
View File
@@ -260,8 +260,8 @@ var libpqPassword = regexp.MustCompile(`(?i)\b(password)\s*=\s*(?:'[^']*'|"[^"]*
// Redact is a log-safe view of a PostgreSQL DSN. It masks URL userinfo
// passwords, `?password=` query values, and libpq `password=` keywords.
// Unrecognised input still runs the keyword mask so a parse failure cannot
// print the secret.
// Unrecognised input still runs the userinfo and keyword masks so a parse
// failure cannot print the secret.
func Redact(dsn string) string {
if dsn == "" {
return dsn
@@ -279,5 +279,14 @@ func Redact(dsn string) string {
}
return u.String()
}
// A URL whose password has an unencoded # / ? or % does not parse; its
// password still runs from the first : after the scheme to the last @.
if i := strings.Index(dsn, "://"); i >= 0 {
if at := strings.LastIndex(dsn, "@"); at > i {
if c := strings.Index(dsn[i+3:at], ":"); c >= 0 {
dsn = dsn[:i+3+c+1] + "****" + dsn[at:]
}
}
}
return libpqPassword.ReplaceAllString(dsn, `${1}=****`)
}
+5
View File
@@ -110,6 +110,11 @@ func TestRedactMasksEveryDSNPasswordForm(t *testing.T) {
{"host=localhost user=u password=secret dbname=d", "secret"},
{"host=localhost password='p a ss' dbname=d", "p a ss"},
{"not a dsn password=stillsecret", "stillsecret"},
// A password with an unencoded # / ? or % makes url.Parse fail.
{"postgres://u:pa#ss@localhost:5432/d?sslmode=disable", "pa#ss"},
{"postgres://u:pa/ss@localhost/d", "pa/ss"},
{"postgresql://u:50%off@localhost/d", "50%off"},
{"postgres://u:a?b@localhost/d", "a?b"},
}
for _, c := range cases {
got := Redact(c.in)