Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
243 changes: 205 additions & 38 deletions internal/db/dsn/redact.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package dsn

import (
"fmt"
"net/url"
"regexp"
"strings"
Expand All @@ -9,6 +10,14 @@ import (
// mask replaces each secret Redact hides.
const mask = "***"

// What ends a parameter's value: in a URL's query only '&', as pgx, net/url and go-sql-driver
// read it, which take a ';' for part of the value; in settings (server=host;password=x) a ';'
// too.
const (
inQuery = "&"
inSettings = "&;"
)

// dsnAddr matches what follows the '@' of a go-sql-driver DSN: a network with its address
// in parentheses, or nothing, then the '/' before the database: tcp(host:3306)/db,
// unix(/tmp/sock)/db, /db.
Expand All @@ -21,13 +30,20 @@ var dsnAddr = regexp.MustCompile(`^([A-Za-z0-9]+\([^)]*\))?/`)
//
// A URL's password runs from the first ':' after the scheme to the last '@', so one that
// holds '@', ':', '/', spaces or %-escapes is hidden whole, and so is the password of a
// malformed URL; that can hide more than the password, never less. The last '@' is that of
// the whole string, unless the URL is in double quotes (Go's %q, as cobra and net/url quote
// one in an error) or backticks (pgx), which then bound it; quoted text is read the same
// way, URLs anywhere in it included. A DSN without a scheme, like go-sql-driver's
// user:pass@tcp(host:3306)/db, is hidden the same way, in quotes or as the whole of s,
// quotes in its password included. The value of a password-like parameter (see
// redactParams) is hidden whole wherever it is, before any quote in it is read.
// malformed URL; that can hide more than the password, never less. If that '@' is in the
// value of a password parameter, as in host:1433?password=p@ss, the rest of the value is
// hidden with it. The last '@' is that of the whole string, unless the URL is in double
// quotes (Go's %q, as cobra and net/url quote one in an error) or backticks (pgx), which
// then bound it; quoted text is read the same way, URLs anywhere in it included. A URL is
// found wherever "://" follows a scheme, even one glued to the text before it, as in
// cobra's error for a URL glued to a flag: unknown flag: --sourcepostgres://user:***@host/db.
// A DSN without a scheme, like go-sql-driver's user:pass@tcp(host:3306)/db, is hidden the
// same way, in quotes or as the whole of s, quotes in its password included. The value of a
// password-like parameter (see secretValues) is hidden whole wherever it is, before any
// quote in it is read.
//
// A driver that reads part of what Redact hides as the host or the database, not the
// password, quotes that part in its errors: CheckPassword refuses such URLs.
func Redact(s string) string {
if schemeLen(s) == 0 && userinfo(s, false) > 0 && dsnAddr.MatchString(s[strings.LastIndexByte(s, '@')+1:]) {
return redactOne(s)
Expand All @@ -39,7 +55,12 @@ func Redact(s string) string {
b.WriteString(redactOne(s[text:end]))
text = end
}
starts := schemeStarts(s)
unclosed := "" // quotes that no later quote of their kind closes: none closes a later one either
for i := 0; i < len(s); {
for len(starts) > 0 && starts[0] < i {
starts = starts[1:]
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
c := s[i]
switch {
case c == '?' || c == '&' || c == ';':
Expand All @@ -48,24 +69,27 @@ func Redact(s string) string {
if secretKey(s[key:i]) {
v := i + 1 + len(s[i+1:]) - len(strings.TrimLeft(s[i+1:], " \t"))
flush(v)
if n := valueLen(s[v:]); n > 0 {
if n := valueLen(s[v:], inSettings); n > 0 {
b.WriteString(mask)
text = v + n
}
i, key = text, text
continue
}
key = i + 1
case c == '"' || c == '`':
if end := closingQuote(s, i); end > 0 {
flush(i)
b.WriteByte(c)
b.WriteString(Redact(s[i+1 : end]))
b.WriteByte(c)
i, text, key, quoted = end+1, end+1, end+1, true
continue
case (c == '"' || c == '`') && strings.IndexByte(unclosed, c) < 0:
end := closingQuote(s, i)
if end < 0 {
unclosed += string(c)
break
}
case (i == 0 || !isSchemeChar(s[i-1])) && schemeLen(s[i:]) > 0:
flush(i)
b.WriteByte(c)
b.WriteString(Redact(s[i+1 : end]))
b.WriteByte(c)
i, text, key, quoted = end+1, end+1, end+1, true
continue
case len(starts) > 0 && starts[0] == i:
flush(i)
b.WriteString(redactOne(s[i:]))
return b.String()
Expand All @@ -80,15 +104,75 @@ func Redact(s string) string {
}

// redactOne hides the secrets of one connection string: the password between the first
// ':' after the scheme and the last '@', and the value of each password-like parameter.
// ':' after the scheme and the last '@' (see passwordEnd), and the value of each
// password-like parameter, read as a URL's query if t has a scheme.
func redactOne(t string) string {
n := schemeLen(t)
head, rest := t[:n], t[n:]
if colon := userinfo(rest, n > 0); colon > 0 {
at := strings.LastIndexByte(rest, '@')
rest = rest[:colon] + mask + rest[at:]
rest = rest[:colon] + mask + rest[passwordEnd(rest, strings.LastIndexByte(rest, '@')):]
} else if start, end := portPassword(rest); n > 0 && start > 0 {
rest = rest[:start] + mask + rest[end:]
}
if n > 0 {
return head + redactParams(rest, inQuery)
}
return head + redactParams(rest)
return redactParams(rest, inSettings)
}

// passwordEnd returns where the password that ends at rest[at], the last '@', is hidden to:
// at, unless that '@' is in the value of a password-like parameter in the query, as in
// host:1433?password=p@ss, where it starts no host. Then all of rest is hidden: whether the
// '@' ends a password with a '?' in it or is part of the value, both are secret, and what
// follows the value is no host to show.
func passwordEnd(rest string, at int) int {
q := strings.IndexByte(rest, '?')
if q < 0 || q > at {
return at
}
for _, v := range secretValues(rest[q:], inQuery) {
if q+v[0] <= at && at < q+v[1] {
return len(rest)
}
}
return at
}

// portPassword returns where a password may stand in place of a port in rest, the part of
// a URL after its scheme, when no '@' ends a user name and password in its host part:
// after the ':' of a host whose "port" is no number, as in postgres://app:s3cret, which
// lacks its "@host", up to the '/', '?' or '#' that ends the host part, as only those end
// one in a URL (a password may hold a ';' or an '&'). It returns 0, 0 if there is none. A
// port that is a number stays, after each host of a list (h1:5432,h2:5433), and a ':' in
// brackets ([::1]) or parentheses (tcp(host:3306)) is no port's.
func portPassword(rest string) (start, end int) {
depth, bad := 0, -1
end = len(rest)
for i := 0; i < end; i++ {
switch c := rest[i]; {
case c == '[' || c == '(':
depth++
case (c == ']' || c == ')') && depth > 0:
depth--
case depth > 0:
case c == '/' || c == '?' || c == '#':
end = i
case c == '@':
return 0, 0
case c == ':' && bad < 0:
j := i + 1
for j < len(rest) && '0' <= rest[j] && rest[j] <= '9' {
j++
}
if j < len(rest) && strings.IndexByte(",/?#", rest[j]) < 0 {
bad = i + 1
}
}
}
if bad < 0 {
return 0, 0
}
return bad, end
}

// userinfo returns the index after the ':' that starts a password in rest, the part of a
Expand All @@ -108,12 +192,73 @@ func userinfo(rest string, scheme bool) int {
return colon + 1
}

// redactParams hides the value of each password-like parameter in t, in a URL's query
// (?password=x&...) or in semicolon-separated settings (user id=sa;password=x): one whose
// name, read percent-decoded and in any case, ends in password, passwd or pwd (password,
// sslpassword, Pwd, pass%77ord).
func redactParams(t string) string {
// CheckPassword returns an error, naming connStr redacted, if the driver for connStr would
// read part of what Redact hides in it as something other than a password, like the user
// name, the host or the database, which the driver's errors quote: failed to connect to
// `user=app database=s3cret@host/db`. Redact ends a URL's password at the last '@' (see
// passwordEnd). pgx (postgres://, postgresql://) ends the user name and password at the
// first '@' before any '/', even one after a '?'; net/url, which the SQL Server driver
// parses with, ends the host at the first '/', '?' or '#'; and go-sql-driver (mysql://,
// mysql+tcp://) reads the database after the last '/'.
func CheckPassword(connStr string) error {
n := schemeLen(connStr)
rest := connStr[n:]
colon := userinfo(rest, true)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Require an authority userinfo delimiter

With a passwordless URL that has a port and a raw @ in a query value after a path, userinfo returns the port's colon as colon; the PostgreSQL and SQL Server checks then reject, for example, postgres://host:5432/db?application_name=a@b, even though the drivers treat that @ as query data. Only run the ambiguity checks when the colon belongs to actual user:password@ authority userinfo, so valid connections like these are not blocked.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This refusal is on purpose; the PR body lists it under behaviour changes. postgres://host:5432/db?application_name=a@b has the same shape as postgres://user:4321/s3cret@host/db, which is the verifier's digits-slash leak. In both, the text from the first : to the last @ contains a /, and pgx reads no userinfo because the / comes before the @. In the second URL, pgx takes the user name for the host, 4321 for the port and s3cret@host/db for the database, and v1.1.3 printed failed to connect to `user=me database=s3cret@host:5432/db` . Nothing in the string says whether the colon is a port's or a password's. A check that let the first URL through, when no userinfo password is visible to the driver, would let the second through too.

Redact can't tell them apart either. It prints the first URL as postgres://host:***@b, hiding the port, the database and part of the parameter, so it is useless in a migration header anyway. The error says to write %40, which pgx and net/url both decode in a query value. With that, postgres://host:5432/db?application_name=a%40b passes and is shown in full. The changelog in #32 states the trade-off. No change.

at := strings.LastIndexByte(rest, '@')
end := at
if colon > 0 {
end = passwordEnd(rest, at)
}
var ambiguous bool
var fix string
switch strings.ToLower(connStr[:n]) {
case "postgres://", "postgresql://":
fix = "percent-encode '@' and '/' in its user name and password, and any '@' after its host"
if colon > 0 {
ambiguous = strings.ContainsAny(rest[:end], "@/")
} else if first := strings.IndexAny(rest, "@/"); first >= 0 && rest[first] == '@' {
// No password ends at an '@', but pgx still ends a user name at the first one,
// even in a password parameter's value: it would read the start of the value
// as part of the user name, and the rest as the host.
secrets := secretValues(rest, inQuery)
ambiguous = len(secrets) > 0 && secrets[0][0] < first

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Allow @ in PostgreSQL query passwords

When a PostgreSQL URL omits the database path and supplies its password in the query, such as postgres://host?password=a@b, pgx parses @ as part of the query value, not as a user/host delimiter. This condition instead treats the query password as ambiguous, so NewDriver rejects an otherwise valid URL before connecting. Only reject @ when it falls in the URL authority that pgx parses as userinfo or host.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

pgx v5.11.0 doesn't parse it that way. Its URL parser matches libpq's, and pgconn/parse_url.go says so: "only a '/' stops the search, so a '@' anywhere before the path -- even inside what looks like a query string -- is treated as the userinfo terminator". pgconn.ParseConfig on this branch's go.mod gives:

postgres://host?password=a@b     -> user="host?password=a" host="b" database="" password=""
postgres://host/db?password=a@b  -> user=<OS user> host="host" database="db" password="a@b"
postgres://u@host?password=a@b   -> user="u" host="host" database="" password="a@b"

In the first URL, pgx would connect to host b as user host?password=a, and its error would quote both: the start and the end of the password. That is the case this condition refuses. The other two forms are accepted, because pgx reads a@b as the password there, as Redact does. TestCheckPassword covers the first and second: postgres://host?sslmode=disable&password=s3cret@s3cret is refused, and postgres://host/db?password=s3cret@s3cret passes. No change.

}
case "sqlserver://":
fix = "percent-encode '/', '?' and '#' in its user name and password, and any '@' after its host"
ambiguous = colon > 0 && strings.ContainsAny(rest[:end], "/?#")
case "mysql://", "mysql+tcp://":
fix = "end it with /database after the address, and percent-encode any '@' after that '/'"
ambiguous = colon > 0 && (end != at || !strings.Contains(rest[at:], "/"))
}
if !ambiguous {
return nil
}
// No ':' after the URL: Redact, which main prints errors through, would take one before
// the '@' in fix for a password's start.
return fmt.Errorf("can't tell where the password ends in %q; %s", Redact(connStr), fix)
}

// redactParams hides the value of each password-like parameter in t (see secretValues).
func redactParams(t, ends string) string {
var b strings.Builder
written := 0
for _, v := range secretValues(t, ends) {
if v[1] > v[0] {
b.WriteString(t[written:v[0]])
b.WriteString(mask)
written = v[1]
}
}
b.WriteString(t[written:])
return b.String()
}

// secretValues returns where the value of each password-like parameter in t starts and
// ends, in a URL's query (?password=x&...) or in semicolon-separated settings (user
// id=sa;password=x), whichever ends says t holds: one whose name, read percent-decoded and
// in any case, ends in password, passwd or pwd (password, sslpassword, Pwd, pass%77ord).
func secretValues(t, ends string) [][2]int {
var values [][2]int
key := 0 // where the name before the next '=' starts
for i := 0; i < len(t); i++ {
switch t[i] {
Expand All @@ -125,16 +270,12 @@ func redactParams(t string) string {
continue
}
v := i + 1 + len(t[i+1:]) - len(strings.TrimLeft(t[i+1:], " \t"))
b.WriteString(t[:v])
n := valueLen(t[v:])
if n > 0 {
b.WriteString(mask)
}
t, i, key = t[v+n:], -1, 0
end := v + valueLen(t[v:], ends)
values = append(values, [2]int{v, end})
i, key = end-1, end
}
}
b.WriteString(t)
return b.String()
return values
}

// secretKey reports whether a parameter name is password-like.
Expand All @@ -146,10 +287,11 @@ func secretKey(name string) bool {
return strings.HasSuffix(name, "password") || strings.HasSuffix(name, "passwd") || strings.HasSuffix(name, "pwd")
}

// valueLen is the length of the parameter value v starts with: up to the next '&' or ';'
// valueLen is the length of the parameter value v starts with: up to the next byte of ends
// outside braces or quotes (password={a;b}), where a doubled closing brace or quote stands
// for itself.
func valueLen(v string) int {
// for itself. A value that holds a URL, outside braces or quotes, runs to the end of v:
// what ends it is the URL's own, like the '@' after its password.
func valueLen(v, ends string) int {
start := 0
if v != "" && strings.IndexByte("{\"'`", v[0]) >= 0 {
closer := v[0]
Expand All @@ -168,7 +310,7 @@ func valueLen(v string) int {
}
}
}
if i := strings.IndexAny(v[start:], "&;"); i >= 0 {
if i := strings.IndexAny(v[start:], ends); i >= 0 && (start > 0 || !strings.Contains(v[:i], "://")) {
return start + i
}
return len(v)
Expand All @@ -188,6 +330,31 @@ func closingQuote(s string, open int) int {
return -1
}

// schemeStarts returns where the scheme of each URL in s starts, in order: at the first
// letter of the scheme characters before each "://", which can be glued to the text before
// them, as in --sourcepostgres://. Each byte is looked at a bounded number of times.
func schemeStarts(s string) []int {
var starts []int
for at := strings.Index(s, "://"); at >= 0; {
start := at
for start > 0 && isSchemeChar(s[start-1]) {
start--
}
for start < at && !isLetter(s[start]) {
start++
}
if start < at {
starts = append(starts, start)
}
next := strings.Index(s[at+3:], "://")
if next < 0 {
break
}
at += 3 + next
}
return starts
}

// schemeLen is the length of the URL scheme and "://" that t starts with, or 0.
func schemeLen(t string) int {
if t == "" || !isLetter(t[0]) {
Expand Down
Loading
Loading