diff --git a/internal/db/dsn/redact.go b/internal/db/dsn/redact.go index 4b3471a..4935b63 100644 --- a/internal/db/dsn/redact.go +++ b/internal/db/dsn/redact.go @@ -1,6 +1,7 @@ package dsn import ( + "fmt" "net/url" "regexp" "strings" @@ -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. @@ -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) @@ -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:] + } c := s[i] switch { case c == '?' || c == '&' || c == ';': @@ -48,7 +69,7 @@ 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 } @@ -56,16 +77,19 @@ func Redact(s string) string { 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() @@ -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 @@ -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) + 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 + } + 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] { @@ -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. @@ -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] @@ -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) @@ -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]) { diff --git a/internal/db/dsn/redact_test.go b/internal/db/dsn/redact_test.go index 55e4fb2..7359798 100644 --- a/internal/db/dsn/redact_test.go +++ b/internal/db/dsn/redact_test.go @@ -4,6 +4,10 @@ import ( "net/url" "strings" "testing" + "time" + + gomysql "github.com/go-sql-driver/mysql" + "github.com/jackc/pgx/v5/pgconn" ) func TestRedact(t *testing.T) { @@ -42,6 +46,19 @@ func TestRedact(t *testing.T) { {"URL inside quoted prose", `error: "connecting to postgres://user:s3cret@host/db failed"`, `error: "connecting to postgres://user:***@host/db failed"`}, + // A URL without the '@' and host after its password: what stands in the place of a + // port is hidden, unless it is a number. + {"password without @host", "postgres://app:s3cret", "postgres://app:***"}, + {"password without @host, then a path", "postgres://app:s3cret/db?sslmode=disable", "postgres://app:***/db?sslmode=disable"}, + {"sqlserver password without @host", "sqlserver://sa:s3cret?database=app", "sqlserver://sa:***?database=app"}, + {"mysql password without @address", "mysql://root:s3cret", "mysql://root:***"}, + {"IPv6 host and port", "postgres://[::1]:5432/app", "postgres://[::1]:5432/app"}, + {"hosts and ports", "postgres://h1:5432,h2:5433/app", "postgres://h1:5432,h2:5433/app"}, + {"password after a later host", "postgres://h1:5432,app:s3cret/app", "postgres://h1:5432,app:***/app"}, + {"empty port", "postgres://host:/app", "postgres://host:/app"}, + {"';' in a password without @host", "postgres://app:s3;cret", "postgres://app:***"}, + {"'&' in a password without @host", "sqlserver://sa:s3&cret?database=app", "sqlserver://sa:***?database=app"}, + // nothing to hide {"no password", "postgres://user@host/app", "postgres://user@host/app"}, {"empty password", "postgres://user:@host/app", "postgres://user:@host/app"}, @@ -55,22 +72,37 @@ func TestRedact(t *testing.T) { {"pwd parameter, any case", "sqlserver://host?database=app&PWD=s3cret&encrypt=disable", "sqlserver://host?database=app&PWD=***&encrypt=disable"}, {"sslpassword", "postgres://user:s3cret@host/app?sslpassword=k3y", "postgres://user:***@host/app?sslpassword=***"}, + // In a URL's query, only '&' ends a value, as pgx, net/url and go-sql-driver read it, so + // settings in a value are hidden from the password on. {"settings in a value", "sqlserver://host?database=app&odbc=user id=sa;Password=s3cret;app name=x", - "sqlserver://host?database=app&odbc=user id=sa;Password=***;app name=x"}, + "sqlserver://host?database=app&odbc=user id=sa;Password=***"}, + {"';' in a password parameter", "postgres://app@host/db?password=s3cret;s3cret&sslmode=disable", + "postgres://app@host/db?password=***&sslmode=disable"}, + // a password parameter whose value holds a URL runs to the end + {"URL in a password setting", "password=postgres://u:first;s3cret@host/db", "password=***"}, + {"URL in a password setting, in prose", "failed: pwd=postgres://u:first;s3cret@host/db", "failed:***@host/db"}, {"spaces around =", "sqlserver://host?user id=sa&password = s3cret", "sqlserver://host?user id=sa&password = ***"}, {"value with spaces", "sqlserver://host?password=my s3cret&database=app", "sqlserver://host?password=***&database=app"}, - {"value in braces", "sqlserver://host?odbc=uid=sa;pwd={a;b}}c};database=app", - "sqlserver://host?odbc=uid=sa;pwd=***;database=app"}, - {"value in quotes", "sqlserver://host?odbc=uid=sa;pwd='a;b''c';database=app", - "sqlserver://host?odbc=uid=sa;pwd=***;database=app"}, - {"text after the closing brace", "sqlserver://host?odbc=pwd={a;b}s3cret;database=app", - "sqlserver://host?odbc=pwd=***;database=app"}, + {"value in braces", "sqlserver://host?odbc=uid=sa;pwd={a&b}}c}&database=app", + "sqlserver://host?odbc=uid=sa;pwd=***&database=app"}, + {"value in quotes", "sqlserver://host?odbc=uid=sa;pwd='a&b''c'&database=app", + "sqlserver://host?odbc=uid=sa;pwd=***&database=app"}, + {"text after the closing brace", "sqlserver://host?odbc=pwd={a&b}s3cret&database=app", + "sqlserver://host?odbc=pwd=***&database=app"}, {"percent-encoded name", "postgres://app@host/db?pass%77ord=s3cret&sslmode=disable", "postgres://app@host/db?pass%77ord=***&sslmode=disable"}, // A value runs to ';' or '&', so here one hides the rest: more than the password, not less. {"keyword=value settings", "cannot parse `host=db sslpassword=k3y password=s3cret`", "cannot parse `host=db sslpassword=***`"}, {"userinfo and parameter", "sqlserver://sa:s3cret@host?database=app&password=s3cret", "sqlserver://sa:***@host?database=app&password=***"}, + // With a ':' before it, an '@' in a parameter's value would end a password that starts + // at the ':': the value is hidden whole with it. + {"parameter holding an @, after a port", "sqlserver://host:1433?database=app&password=s3cret@s3cret", + "sqlserver://host:***"}, + {"parameter holding an @, then others", "postgres://host:5432/app?password=s3cret@s3cret&sslmode=disable", + "postgres://host:***"}, + {"parameter holding an @, without a port", "sqlserver://host?database=app&password=s3cret@s3cret", + "sqlserver://host?database=app&password=***"}, // text holding connection strings, as errors and logs do {"after text", "unsupported scheme in postgress://user:s3cret@host/app", "unsupported scheme in postgress://user:***@host/app"}, @@ -82,6 +114,17 @@ func TestRedact(t *testing.T) { "cannot parse `POSTGRES://user:***@host/app`: failed to parse as keyword/value"}, {"quoted DSN without a scheme", `unknown command "root:s3cret@tcp(host:3306)/app" for "dbdiff"`, `unknown command "root:***@tcp(host:3306)/app" for "dbdiff"`}, + // pflag quotes a URL glued to a flag whole, after the flag's dashes or letters + {"URL glued to a shorthand flag", "unknown shorthand flag: 'p' in -postgres://user:s3cret@host/app", + "unknown shorthand flag: 'p' in -postgres://user:***@host/app"}, + {"URL glued to a long flag", "unknown flag: --sourcepostgres://user:s3cret@host/app", + "unknown flag: --sourcepostgres://user:***@host/app"}, + {"URL after two dashes", "unknown flag: --mysql://root:s3cret@tcp(host:3306)/app", + "unknown flag: --mysql://root:***@tcp(host:3306)/app"}, + {"URL after three dashes", "bad flag syntax: ---sqlserver://sa:s3cret@host?database=app", + "bad flag syntax: ---sqlserver://sa:***@host?database=app"}, + {"URL after a digit", "unknown shorthand flag: '1' in -1postgres://user:s3cret@host/app", + "unknown shorthand flag: '1' in -1postgres://user:***@host/app"}, {"quoted prose", `reason: "user root: denied to root@host"`, `reason: "user root: denied to root@host"`}, {"driver error prose", "Error 1045 (28000): Access denied for user 'root'@'172.17.0.1' (using password: YES)", "Error 1045 (28000): Access denied for user 'root'@'172.17.0.1' (using password: YES)"}, @@ -104,7 +147,7 @@ func TestRedact(t *testing.T) { // scheme, in a percent-encoded query parameter, and in braces in settings (go test -fuzz // FuzzRedactPassword explores beyond these seeds). func FuzzRedactPassword(f *testing.F) { - for _, p := range []string{"s3cret", "p@ss:w/rd", "a\"b`c d", "x://y@z", "pwd=a;b", "%zz%40", "{a;b}}", "a\"b\"c", "x`y`z"} { + for _, p := range []string{"s3cret", "p@ss:w/rd", "a\"b`c d", "x://y@z", "pwd=a;b", "%zz%40", "{a;b}}", "a\"b\"c", "x`y`z", "a?pwd=b"} { f.Add("app", p) } f.Fuzz(func(t *testing.T, user, pass string) { @@ -117,13 +160,133 @@ func FuzzRedactPassword(f *testing.F) { "server=host;user id=" + user + ";password={" + strings.ReplaceAll(pass, "}", "}}") + "};database=db": "server=host;user id=" + user + ";password=***;database=db", "postgres://" + user + "@host/db?pass%77ord=" + url.QueryEscape(pass) + "&sslmode=disable": "postgres://" + user + "@host/db?pass%77ord=***&sslmode=disable", } - for _, form := range []string{"postgres://%s@host/db", "mysql://%s@tcp(host:3306)/db", "sqlserver://%s@host?database=db", "%s@tcp(host:3306)/db"} { + for _, form := range []string{"postgres://%s@host/db", "mysql://%s@tcp(host:3306)/db", "sqlserver://%s@host?database=db", "%s@tcp(host:3306)/db", + "unknown flag: --sourcepostgres://%s@host/db", "unknown shorthand flag: 'p' in -postgres://%s@host/db"} { cases[strings.Replace(form, "%s", user+":"+pass, 1)] = strings.Replace(form, "%s", user+":***", 1) } for in, want := range cases { - if got := Redact(in); got != want { + // After a '?' in the password, a password parameter's value can hold the '@' that + // ends it: then all that follows the ':' is hidden (see passwordEnd). + got := Redact(in) + hidesAll := strings.Contains(pass, "?") && strings.HasSuffix(got, ":"+mask) && strings.HasPrefix(want, got) + if got != want && !hidesAll { t.Errorf("password %q: Redact(%q) = %q, want %q", pass, in, got, want) } } }) } + +// CheckPassword lets through each URL whose driver reads as the password all that Redact +// hides, and refuses, without the password, those whose driver would read part of it as the +// host or the database. +func TestCheckPassword(t *testing.T) { + for _, tt := range []struct { + url string + ok bool + }{ + {"postgres://app:s3cret@host:5432/db?sslmode=disable", true}, + {"postgresql://app:s3cret?#:x@host/db", true}, // pgx's password runs to the first '@' + {"postgres://app:p%40ss%2Fw@host/db", true}, + {"postgres://app@host/db?application_name=a@b", true}, // no password in the userinfo + {"postgres://host/db?password=s3cret", true}, + {"sqlserver://sa:p@ss:w@host?database=db", true}, // net/url's runs to the host's last '@' + {"mysql://root:p@ss/w:rd?#@tcp(host:3306)/db", true}, // go-sql-driver's, to the last '@' before the last '/' + {"MYSQL+TCP://root:s3cret@tcp(host:3306)/db?parseTime=true", true}, + {"mariadb://app:a/s3cret@host/db", true}, // no driver: NewDriver refuses the scheme + {"postgres://host/db?password=s3cret@s3cret", true}, // pgx: no user name before the '/' + {"sqlserver://host?database=db&password=s3cret@s3cret", true}, + + {"postgres://app:/s3cret@host:5432/db", false}, // pgx: host app, database s3cret@host:5432/db + {"postgres://app:4321/s3cret@host/db", false}, // pgx: port 4321 + {"postgres://app:p@s3cret@host/db", false}, // pgx: password p, host s3cret@host + {"postgres://app:s3cret@host/db?x=a@b", false}, // the password Redact hides runs to a@ + {"sqlserver://sa:4321/s3cret@host?database=db", false}, + {"sqlserver://sa:a?s3cret@host?database=db", false}, + {"mysql://root:s3cret/x@tcp(host:3306)", false}, // go-sql-driver: database x@tcp(host:3306) + {"mysql://root:s3cret@tcp(host:3306)", false}, + {"mysql+tcp://root:s3cret@tcp(host:3306)/db?x=a@b", false}, + // an '@' in a password parameter's value, with a ':' before it, or, for pgx, before any '/' + {"postgres://host:5432/db?password=s3cret@s3cret", false}, + {"postgres://host?sslmode=disable&password=s3cret@s3cret", false}, // pgx: user host?sslmode=disable&password=s3cret + {"sqlserver://host:1433?database=db&password=s3cret@s3cret", false}, + {"mysql://root@tcp(host:3306)/db?password=s3cret@s3cret&x=/", false}, + } { + err := CheckPassword(tt.url) + if tt.ok != (err == nil) || err != nil && (strings.Contains(err.Error(), "s3cret") || !strings.Contains(err.Error(), "***")) { + t.Errorf("CheckPassword(%q) = %v, want ok=%v and no password", tt.url, err, tt.ok) + } + // main prints errors through Redact, which must leave this one as it is. + if err != nil && Redact("Error: failed to initialize driver: "+err.Error()) != "Error: failed to initialize driver: "+err.Error() { + t.Errorf("CheckPassword(%q): Redact changes its error to %q", tt.url, Redact(err.Error())) + } + } +} + +// A URL CheckPassword lets through is one whose driver, parsing it the way dbdiff's driver +// does, reads as the password all that Redact hides, or fails (go test -fuzz +// FuzzCheckPassword explores beyond these seeds). +func FuzzCheckPassword(f *testing.F) { + for _, s := range [][3]string{{"app", "s3cret", "host:5432/db?sslmode=disable"}, {"app", "s3cret?#:x", "host/db"}, + {"app", "p%40ss%2Fw", "host/db"}, {"sa", "p@ss:w", "host?database=db"}, {"root", "p@ss/w:rd?#", "tcp(host:3306)/db"}, + {"app", "4321/s3cret", "host/db"}, {"app", "s3cret", "host/db?x=a@b"}, {"a@b", "s3cret", "host"}} { + f.Add(s[0], s[1], s[2]) + } + f.Fuzz(func(t *testing.T, user, pass, tail string) { + for _, scheme := range []string{"postgres://", "sqlserver://", "mysql://"} { + u := scheme + user + ":" + pass + "@" + tail + rest := u[len(scheme):] + if CheckPassword(u) != nil || userinfo(rest, true) == 0 { + continue + } + at := strings.LastIndexByte(rest, '@') + hidden := rest[strings.IndexByte(rest[:at], ':')+1 : passwordEnd(rest, at)] + var got, want string + switch scheme { + case "postgres://": + // pgx drops the spaces around a password, then looks for one elsewhere. + var err error + if want, err = url.PathUnescape(strings.Trim(hidden, " ")); err != nil || want == "" { + continue + } + cfg, err := pgconn.ParseConfig(u) + if err != nil { + continue + } + got = cfg.Password + case "sqlserver://": + p, err := url.Parse(u) + if err != nil { + continue + } + if p.User != nil { + got, _ = p.User.Password() + } + want, _ = url.PathUnescape(hidden) + case "mysql://": + cfg, err := gomysql.ParseDSN(rest) + if err != nil { + continue + } + got, want = cfg.Passwd, hidden + } + if got != want { + t.Errorf("%q: the driver reads the password %q, Redact hides %q", u, got, hidden) + } + } + }) +} + +// Redact takes time linear in its input: a long run of letters, or of quotes that never +// close, made it scan the rest of the input again at each byte. +func TestRedactTakesLinearTime(t *testing.T) { + for _, s := range []string{strings.Repeat("a", 300000), strings.Repeat(`"\`, 300000), strings.Repeat("`a", 150000)} { + in := s + " postgres://app:s3cret@host/db" + start := time.Now() + got := Redact(in) + // ponytail: a wall-clock bound, wide enough for -race on a slow runner; the quadratic + // scans took about 30 s for the first two, without -race. + if d := time.Since(start); d > 10*time.Second || strings.Contains(got, "s3cret") { + t.Errorf("Redact of %d bytes took %v, and left the password: %v", len(in), d, strings.Contains(got, "s3cret")) + } + } +} diff --git a/internal/db/mysql/mysql.go b/internal/db/mysql/mysql.go index bc651e7..2914463 100644 --- a/internal/db/mysql/mysql.go +++ b/internal/db/mysql/mysql.go @@ -3,7 +3,9 @@ package mysql import ( "context" "database/sql" + "errors" "fmt" + "strings" "time" gomysql "github.com/go-sql-driver/mysql" @@ -20,24 +22,37 @@ func New() *Driver { return &Driver{} } -// Connect establishes a connection to the MySQL database -func (d *Driver) Connect(ctx context.Context, connStr string, sslMode string, timeout time.Duration) error { - // Clean up the connStr if it starts with mysql:// as go-sql-driver expects user:pass@tcp(host:port)/dbname - // This simple conversion handles standard format but might need more logic - // e.g. mysql://user:pass@host:port/dbname -> user:pass@tcp(host:port)/dbname - // First, let's let the DB connect with standard sql.Open - - // Remove the "mysql://" prefix for the go-sql-driver +// parseDSN reads connStr, a go-sql-driver DSN after mysql:// or mysql+tcp:// in any case +// (mysql://user:pass@tcp(host:3306)/db), as go-sql-driver does. +func parseDSN(connStr string) (cfg *gomysql.Config, err error) { dsn := connStr - if len(dsn) > 8 && dsn[:8] == "mysql://" { - dsn = dsn[8:] - // Replace the first '/' with '@tcp(host)/' if no '@' or 'tcp(' exists? - // A full parser might be better here, but let's assume valid go-sql-driver DSN for now if they strip it + if lower := strings.ToLower(dsn); strings.HasPrefix(lower, "mysql://") || strings.HasPrefix(lower, "mysql+tcp://") { + dsn = dsn[strings.Index(dsn, "://")+3:] } + defer func() { + // go-sql-driver panics on strict, a parameter it dropped, with a message that quotes + // nothing of the DSN. + if r := recover(); r != nil { + cfg, err = nil, fmt.Errorf("invalid mysql connection string: %v", r) + } + }() + if cfg, err = gomysql.ParseDSN(dsn); err != nil { + // Its errors that start "invalid DSN: " quote nothing of the DSN. The others quote a + // part of it, which can be part of the password: the database name or the network it + // reads from a DSN without /database after the address, or a parameter's value. + if !strings.HasPrefix(err.Error(), "invalid DSN: ") { + err = errors.New("go-sql-driver can't read it; it should look like mysql://user:password@tcp(host:3306)/database?name=value") + } + return nil, fmt.Errorf("invalid mysql connection string: %w", err) + } + return cfg, nil +} - cfg, err := gomysql.ParseDSN(dsn) +// Connect establishes a connection to the MySQL database +func (d *Driver) Connect(ctx context.Context, connStr string, sslMode string, timeout time.Duration) error { + cfg, err := parseDSN(connStr) if err != nil { - return fmt.Errorf("invalid mysql connection string: %w", err) + return err } // A migration file holds many statements, and apply runs it in one Exec. cfg.MultiStatements = true diff --git a/internal/db/mysql/mysql_integration_test.go b/internal/db/mysql/mysql_integration_test.go index 0aeaafe..1e79fa2 100644 --- a/internal/db/mysql/mysql_integration_test.go +++ b/internal/db/mysql/mysql_integration_test.go @@ -66,6 +66,14 @@ func TestMySQLIntrospectionIntegration(t *testing.T) { require.NoError(t, err) defer driver.Close() + // The other schemes NewDriver takes reach the same server as the same user. + for _, url := range []string{"MYSQL://" + dsn, "mysql+tcp://" + dsn} { + other, err := db.NewDriver(url) + require.NoError(t, err) + require.NoError(t, other.Connect(ctx, url, "disable", 20*time.Second), url) + other.Close() + } + // 3. Setup dummy schema setupSQL := ` CREATE TABLE products ( diff --git a/internal/db/mysql/mysql_test.go b/internal/db/mysql/mysql_test.go index de2403e..afbe305 100644 --- a/internal/db/mysql/mysql_test.go +++ b/internal/db/mysql/mysql_test.go @@ -4,6 +4,7 @@ import ( "context" "reflect" "regexp" + "strings" "testing" "time" @@ -289,3 +290,44 @@ func TestIntrospectMocked(t *testing.T) { t.Errorf("there were unfulfilled expectations: %s", err) } } + +// Connect reads the go-sql-driver DSN after each scheme NewDriver takes, in any case: it used +// to strip only mysql://, so go-sql-driver read MYSQL or mysql+tcp as the user name. +func TestParseDSN(t *testing.T) { + for _, url := range []string{"mysql://root:p@ss/w:rd@tcp(db:3306)/app", "MYSQL://root:p@ss/w:rd@tcp(db:3306)/app", + "mysql+tcp://root:p@ss/w:rd@tcp(db:3306)/app"} { + cfg, err := parseDSN(url) + if err != nil || cfg.User != "root" || cfg.Passwd != "p@ss/w:rd" || cfg.Addr != "db:3306" || cfg.DBName != "app" { + t.Errorf("%s: got %+v, %v", url, cfg, err) + } + } +} + +// Without a /database after the address, go-sql-driver reads the database, or the network, +// from the password, and quotes it in its error; Connect's error holds none of it. +func TestConnectParseErrorHidesPassword(t *testing.T) { + for _, url := range []string{ + "mysql://root:QZXa/QZYb@tcp(db:3306)", // go-sql-driver: default addr for network 'root:QZXa' unknown + "mysql://root:QZXa/QZYb%zz@tcp(db:3306)", // go-sql-driver: invalid dbname "QZYb%zz@tcp(db:3306)" + "mysql://ro=ot:QZXa/QZYb%zz@tcp(db:3306)", // Redact reads a bare DSN whose user name has a '=' as prose + "ro=ot:QZXa/QZYb%zz@tcp(db:3306)", + "mysql://root:QZXa/QZYb?password=%zz", // without the bad escape: default addr for network 'root:QZXa' + "mysql://u:p@tcp(db:3306)/app?password=QZX%zz;QZY", // Redact used to end the value at the ';' + "mysql://u:p@tcp(db:3306)/app?password=%zz&strict=true", + } { + err := New().Connect(context.Background(), url, "disable", time.Second) + if err == nil || strings.Contains(err.Error(), "QZX") || strings.Contains(err.Error(), "QZY") || strings.Contains(err.Error(), "zz") { + t.Errorf("%s: expected an error without the password, got %v", url, err) + } + } + // Errors that quote nothing of the DSN are passed on. + if err := New().Connect(context.Background(), "mysql://root:QZXa@tcp(db:3306/app", "disable", time.Second); err == nil || + !strings.Contains(err.Error(), "invalid DSN: network address not terminated (missing closing brace)") { + t.Errorf("expected go-sql-driver's own reason, got %v", err) + } + // go-sql-driver panics on strict, a parameter it dropped: Connect returns an error instead. + if err := New().Connect(context.Background(), "mysql://root:QZXa@tcp(db:3306)/app?strict=true", "disable", time.Second); err == nil || + !strings.Contains(err.Error(), "strict mode has been removed") { + t.Errorf("expected an error for strict, got %v", err) + } +} diff --git a/internal/db/registry.go b/internal/db/registry.go index 945352c..c91c57c 100644 --- a/internal/db/registry.go +++ b/internal/db/registry.go @@ -6,6 +6,7 @@ import ( "slices" "strings" + "github.com/meru143/dbdiff/internal/db/dsn" "github.com/meru143/dbdiff/internal/db/mssql" "github.com/meru143/dbdiff/internal/db/mysql" "github.com/meru143/dbdiff/internal/db/postgres" @@ -21,7 +22,13 @@ const MigrationsTable = "_dbdiff_migrations" // - postgres://, postgresql:// → PostgreSQL driver // - mysql://, mysql+tcp:// → MySQL driver // - sqlserver:// → SQL Server driver +// +// It refuses a URL its driver would read part of the password of as the host or the +// database, which the driver's errors quote (see dsn.CheckPassword). func NewDriver(connStr string) (Driver, error) { + if err := dsn.CheckPassword(connStr); err != nil { + return nil, err + } lower := strings.ToLower(connStr) switch { diff --git a/internal/db/registry_test.go b/internal/db/registry_test.go index 32f196a..d17b2eb 100644 --- a/internal/db/registry_test.go +++ b/internal/db/registry_test.go @@ -34,9 +34,14 @@ func TestIntrospectLeavesOutMigrationsTable(t *testing.T) { } } -// A URL NewDriver refuses stays out of its error: it may hold a password. +// A URL NewDriver refuses stays out of its error: it may hold a password. It refuses those +// whose driver would read part of the password as the host or the database, which the +// driver's errors quote: failed to connect to `user=me database=s3cret@host:5432/db`. func TestNewDriverErrorHidesURL(t *testing.T) { - for _, url := range []string{"postgress://app:s3cret@host/db", "root:s3cret@tcp(host:3306)/db"} { + for _, url := range []string{"postgress://app:s3cret@host/db", "root:s3cret@tcp(host:3306)/db", + "postgres://app:/s3cret@host:5432/db", "postgres://app:4321/s3cret@host:5432/db", + "mysql://app:x/s3cret%zz@tcp(host:3306)", "mysql://app:s3cret/x@tcp(host:3306)", + "sqlserver://sa:4321/s3cret@host:1433?database=db"} { _, err := NewDriver(url) if err == nil || strings.Contains(err.Error(), "s3cret") { t.Errorf("%s: expected an error without the password, got %v", url, err) diff --git a/main.go b/main.go index ff00bb8..6d27110 100644 --- a/main.go +++ b/main.go @@ -193,8 +193,48 @@ func main() { }, }) + hideHelpTopicPasswords(rootCmd) + hideCompletionPasswords(rootCmd) + if err := rootCmd.Execute(); err != nil { fmt.Fprintf(os.Stderr, "Error: %v\n", dsn.Redact(err.Error())) os.Exit(1) } } + +// hideHelpTopicPasswords hides the passwords in the topics given to root's help command: +// cobra's prints one it can't find itself (Unknown help topic [`postgres://...`]), not +// through main's error print. +func hideHelpTopicPasswords(root *cobra.Command) { + root.InitDefaultHelpCmd() + for _, help := range root.Commands() { + if help.Name() == "help" && help.Run != nil { + run := help.Run + help.Run = func(cmd *cobra.Command, args []string) { + for i := range args { + args[i] = dsn.Redact(args[i]) + } + run(cmd, args) + } + } + } +} + +// hideCompletionPasswords hides the passwords in the arguments of cobra's hidden __complete +// command, which shells run for completions: cobra prints those it can't place itself, on +// stderr ([Error] unable to find a command for arguments: [postgres://...]). cobra adds the +// command only once Execute runs, so root's PersistentPreRun, which cobra runs for it with +// the arguments it then passes to its Run, hides them. No completion here reads a URL. +func hideCompletionPasswords(root *cobra.Command) { + pre := root.PersistentPreRun + root.PersistentPreRun = func(cmd *cobra.Command, args []string) { + if cmd.Name() == cobra.ShellCompRequestCmd { + for i := range args { + args[i] = dsn.Redact(args[i]) + } + } + if pre != nil { + pre(cmd, args) + } + } +} diff --git a/main_test.go b/main_test.go index 6363355..d43a4c6 100644 --- a/main_test.go +++ b/main_test.go @@ -2,8 +2,12 @@ package main import ( "bytes" + "io" + "os" "strings" "testing" + + "github.com/spf13/cobra" ) // dbdiff --help opens with what dbdiff does: all three databases, not only PostgreSQL. @@ -19,3 +23,67 @@ func TestRootHelp(t *testing.T) { t.Errorf("help should start with %q, got:\n%s", want, help) } } + +// cobra's help command prints a topic it can't find itself, past main's error print: the +// password in one stays hidden, and a topic it finds still gets its help. +func TestHelpTopicHidesPassword(t *testing.T) { + root := &cobra.Command{Use: "dbdiff"} + root.AddCommand(&cobra.Command{Use: "compare", Short: "Compare two database schemas", Run: func(*cobra.Command, []string) {}}) + hideHelpTopicPasswords(root) + for args, want := range map[string]string{ + "postgres://app:s3cret@host/db": "Unknown help topic [`postgres://app:***@host/db`]", + "compare": "Compare two database schemas", + } { + var out bytes.Buffer + root.SetOut(&out) + root.SetArgs([]string{"help", args}) + if err := root.Execute(); err != nil { + t.Fatal(err) + } + if got := out.String(); strings.Contains(got, "s3cret") || !strings.Contains(got, want) { + t.Errorf("help %s: want %q, without the password, got:\n%s", args, want, got) + } + } +} + +// cobra's __complete command, which shells run for completions, prints the arguments it +// can't place itself, on stderr, past main's error print: the password in one stays hidden, +// and completions still come. +func TestCompletionHidesPassword(t *testing.T) { + root := &cobra.Command{Use: "dbdiff"} + root.AddCommand(&cobra.Command{Use: "compare", Run: func(*cobra.Command, []string) {}}) + hideCompletionPasswords(root) + stderr := os.Stderr + t.Cleanup(func() { os.Stderr = stderr }) + for _, args := range [][]string{ + {cobra.ShellCompRequestCmd, "postgres://app:s3cret@host/db", ""}, // unable to find a command for arguments: [...] + {cobra.ShellCompNoDescRequestCmd, "--bogus", "mysql://app:s3cret@tcp(host:3306)/db", ""}, // Error while parsing flags from args [...] + {cobra.ShellCompRequestCmd, "comp"}, + } { + r, w, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + os.Stderr = w + var out bytes.Buffer + root.SetOut(&out) + root.SetArgs(args) + err = root.Execute() + os.Stderr = stderr + w.Close() + printed, _ := io.ReadAll(r) + r.Close() + if err != nil { + t.Fatal(err) + } + got := out.String() + string(printed) + if strings.Contains(got, "s3cret") { + t.Errorf("%q printed the password:\n%s", args, got) + } + if args[1] == "comp" && !strings.Contains(out.String(), "compare") { + t.Errorf("%q should still complete compare, got:\n%s", args, got) + } else if args[1] != "comp" && !strings.Contains(got, "app:***@") { + t.Errorf("%q should show the URL with its password hidden, got:\n%s", args, got) + } + } +}