Skip to content

Commit 5b43726

Browse files
committed
fix: mask password in DB URL when driver open fails
Prevent database passwords from appearing in error messages when driver.Open(url) fails by masking the URL. This ensures that sensitive credentials are not accidentally exposed in logs or error reports.
1 parent 604248c commit 5b43726

File tree

1 file changed

+28
-1
lines changed

1 file changed

+28
-1
lines changed

database/driver.go

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ package database
77
import (
88
"fmt"
99
"io"
10+
"net/url"
1011
"sync"
1112

1213
iurl "github.com/golang-migrate/migrate/v4/internal/url"
@@ -95,7 +96,12 @@ func Open(url string) (Driver, error) {
9596
return nil, fmt.Errorf("database driver: unknown driver %v (forgotten import?)", scheme)
9697
}
9798

98-
return d.Open(url)
99+
if driverInstance, err := d.Open(url); err != nil {
100+
maskedURL := maskPasswordInURL(url)
101+
return nil, fmt.Errorf("failed to open driver for url %s: %w", maskedURL, err)
102+
} else {
103+
return driverInstance, nil
104+
}
99105
}
100106

101107
// Register globally registers a driver.
@@ -121,3 +127,24 @@ func List() []string {
121127
}
122128
return names
123129
}
130+
131+
func maskPasswordInURL(rawURL string) string {
132+
u, err := url.Parse(rawURL)
133+
if err != nil || u.User == nil {
134+
return rawURL
135+
}
136+
137+
masked := rawURL
138+
if _, hasPassword := u.User.Password(); hasPassword {
139+
140+
masked = u.Scheme + "://" + u.User.Username() + ":******@" + u.Host + u.Path
141+
if u.RawQuery != "" {
142+
masked += "?" + u.RawQuery
143+
}
144+
if u.Fragment != "" {
145+
masked += "#" + u.Fragment
146+
}
147+
}
148+
149+
return masked
150+
}

0 commit comments

Comments
 (0)