diff --git a/CHANGELOG.md b/CHANGELOG.md index a70e897..6f9f89e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,16 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [Unreleased] +## [1.1.5] - 2026-10-29 + +### Security +- **A raw `&` in a password parameter showed the rest of the password**: pgx and the SQL Server driver end a parameter's value at the next `&`, and so did dbdiff when it hid one, so `postgres://user@host/db?sslmode=disable&password=pass&word` was printed as `…&password=***&word`. That reached `validate`'s output and the `-v` and `--debug` logs, on PostgreSQL and SQL Server, and on PostgreSQL, when pgx couldn't read what followed the `&` (`&word`, `&a=b=c`), the error of every command that connects, twice: ``cannot parse `…&password=***&word`: failed to parse as URL (missing key/value separator "=" in URI query parameter: "word")``. It held for `password=`, `sslpassword=`, `pwd=` and the other password parameters, with or without a port, and for settings and DSNs given where a command or a flag value belongs: `server=host;password=pass&word;database=db` was printed as `server=host;password=***&word;database=db`. 1.1.4 and every earlier version do this. A driver can't tell an `&` in a password from the start of the next parameter, and neither can dbdiff, so it now hides all that follows a password parameter's `=`, to the end of the URL or the settings, or to the quote that closes them in an error (see Changed). The drivers read what followed the `&` as parameters, and when the server or the driver refused one, its error quoted it, as PostgreSQL's `unrecognized configuration parameter "word"` does. MySQL's driver has no password parameter: it sends an unknown one to the server as a `SET`. That never logs anyone in, and the server's syntax error quoted the value, `&` or not (`near 'pass' at line 1`), past the 80 characters the server cuts such an error to, across a second parameter, and whether or not the password was also in the user info. Worse, when the value was quoted (`?password=%27pass%27`), MySQL ran the `SET password = 'pass'` it received as a `SET PASSWORD` and changed the logged-in account's own password to it (confirmed on throwaway accounts). **If you ran a MySQL URL carrying a `password=`, `pwd=` or `passwd=` query parameter under 1.1.4 or earlier, that account's password may have been reset to the parameter's value: check and reset the affected MySQL accounts.** dbdiff now refuses a password parameter in a `mysql://` or `mysql+tcp://` URL and says to put the password in the user info, so the `SET` is never sent. For PostgreSQL and SQL Server, where a password parameter is real, dbdiff leaves out a connection error that quotes a token of what it hides, at any length — a parameter name the server rejects (a 1-2 character piece after a raw `&` included, and one holding a quote), one padded with the spaces, tabs or control bytes a `%`-escape decoded to, a setting inside an `options` value, a value go-mssqldb read with a `+` as a space, or go-mssqldb's unquoted duplicate key — and names the URL with that part hidden instead. On PostgreSQL's parse path, pgx repeats some values it rejects, at times escaped or trimmed (`unknown target_session_attrs value`, `unknown channel_binding value`, a missing `sslrootcert`/`sslcert`/`sslkey`/`servicefile` file, `connect_timeout`, `pool_max_conns`, `require_auth`), and quotes the URL it parsed, which a backtick after the password ended early. For a URL with a password parameter, dbdiff now shows only one of a few fixed reasons that name no value (`sslmode is invalid`, `invalid port`), matched against pgx's whole error, after the URL with that part hidden, and the generic parse hint for any other. What still shows, as in every version: a tail which spells a connection setting that an error repeats unquoted or in backticks — such as `options=` reaching the backend (`invalid command-line argument for server process: …`), `host=` or SQL Server's `server=` reaching the resolver (`lookup … no such host`), `port=` in a dial error, or `user=`, `dbname=` or `database=` in pgx's ``failed to connect to `user=… database=…` `` — and the digits-only password with no `@host` noted under 1.1.4 (`postgres://app:20241031/db`), which cannot be told from a port +- Migration files hold what followed the `&` only where such a URL connected: dbdiff writes one once both databases have accepted the connection, and the drivers sent only the part of the password before the `&`, which a server that checks that password refuses. Such a URL connected when nothing checked that password: on a PostgreSQL server with the `trust` method, with an `sslpassword=` and no encrypted client key to open with it, or with a SQL Server `pwd=`, which the driver ignores in a URL; and on PostgreSQL only when what followed the `&` read as settings pgx and the server take, as in `sslpassword=pass&application_name=word` or any dotted custom setting (`word.x=y`), which PostgreSQL accepts. The migration's `-- Source:` or `-- Target:` line then shows that part: if you wrote such a URL, scrub those lines, and change the password wherever it is checked +- A URL given in place of a file or a schema name was printed as given: `tables --schema "$URL"` printed `No tables found in schema: `, `migrate -o "$URL"` printed it in its prompt and its `-v` log line, `compare -o` and `interactive -o` did the same, and `migrate --backup-dir "$URL"` printed it in its `Backup created:` and `Failed to create backup:` `-v` lines. The password in it is hidden now. A URL given to `-o` or `--backup-dir` still becomes directories on disk named after it, with the password in those names; only what dbdiff prints is hidden. `--config "$URL"` printed what followed the last `.` in it, part of the password included, which viper took for the file's type (`Unsupported Config Type "word@host:5432"`); dbdiff no longer reads a URL given for `--config` or in `DBDIFF_CONFIG`, and says it takes a file + +### Changed +- What dbdiff prints of a connection string, in the migration header, `-v` logs, `validate` and errors, now ends at a password parameter: `sqlserver://host?database=db&password=x&encrypt=disable` is printed as `sqlserver://host?database=db&password=***`, and `server=host;password=x;database=db` as `server=host;password=***`. A connection error is replaced by a generic message when it quotes, in single or double quotes, a whole name or value that occurs after the first password parameter's `=`, or names one as go-mssqldb's duplicate key (matched token by token, so an ordinary error that merely contains the user or database name inside a longer word is kept; a token that holds a quote is matched wherever it appears). As a fail-closed trade-off, that also replaces a genuine login error when it quotes a real parameter you wrote **after** the password — a `user id` or an `application_name` equal to the user or database name, or to it with a quote beside it — with `connecting with "…" failed with an error that quotes part of what follows the '=' of its password parameter …`. To keep the other parameters and the real error in view, put the password in the user-info part (`postgres://user:pass%26word@host/db?sslmode=disable`) or, on PostgreSQL and SQL Server, its parameter last; and in a parameter, write an `&` in the password as `%26`, or the driver reads only the part before it. A MySQL URL's password must be in the user info now: a password parameter there is refused, since go-sql-driver never logs in with one (so putting it last would not have protected it either). dbdiff scans a MySQL query for a password parameter from its first `?`, so besides the URLs 1.1.4 refused it also refuses a few contrived ones 1.1.4 connected with, where a `password`/`pwd`/`passwd` token sits after an `=` inside another parameter's value (`?connectionAttributes=password=x`). Connections don't change otherwise: the drivers still read a password parameter up to the next `&`. A faulty parameter after a PostgreSQL password still reports why the URL won't parse when pgx's reason is one of a few fixed ones that name no value (`sslmode is invalid`, `invalid port`), with the password hidden; any other reason gives the generic hint + ## [1.1.4] - 2026-10-28 ### Security @@ -13,6 +23,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). - **A password parameter holding an `@`, after a port, was hidden only up to the `@`**: `sqlserver://host:1433?database=db&password=P@ssw0rd` was printed as `sqlserver://host:***@ssw0rd` in `-v` logs, errors and the migration header. Migration files written from such a URL hold the rest of the password: scrub them and rotate it. dbdiff now hides all of that value, and refuses such a URL (see below) - **A password parameter holding a `;` was hidden only up to the `;`**: pgx reads `postgres://app@host/db?password=pass;word` as the password `pass;word`, which the `-v` logs and the migration header showed as `?password=***;word`. Migration files written from such a URL hold the rest of the password: scrub them and rotate it. In a URL, a parameter's value now runs to the next `&`, as the drivers read it - dbdiff refuses a URL whose driver would read part of the password as the user name, the host or the database, which the driver's errors quote: `postgres://user:/pass@host:5432/db` failed with ``failed to connect to `user=me database=pass@host:5432/db` ``. Such URLs are a PostgreSQL URL with `@` or `/` in its user name or password, a SQL Server URL with `/`, `?` or `#` there, a MySQL URL without `/database` after the address, and one with a password parameter holding an `@` like the one above. The error names the URL with its password hidden and says what to percent-encode or add. A PostgreSQL or SQL Server URL with another `@` after its host, as in `?application_name=a@b`, can be refused too: write that `@` as `%40` +- A MySQL URL with a password and a raw `@` after its `/database`, as in `?connectionAttributes=owner:ops@example`, is refused too, though 1.1.3 connected with it: write that `@` as `%40` ### Fixed - `mysql+tcp://` URLs, and MySQL URLs whose scheme is in upper case, connect as the user they name. dbdiff accepted both, but read the scheme as the user name: `Access denied for user 'mysql+tcp'` diff --git a/README.md b/README.md index 338bd12..a5716e6 100644 --- a/README.md +++ b/README.md @@ -35,7 +35,7 @@ go install github.com/meru143/dbdiff@latest brew install meru143/homebrew-dbdiff/dbdiff # Via release binary (Linux x86-64 shown) -curl -fsSL https://github.com/Meru143/dbdiff/releases/download/v1.1.4/dbdiff_1.1.4_linux_amd64.tar.gz | tar -xz dbdiff +curl -fsSL https://github.com/Meru143/dbdiff/releases/download/v1.1.5/dbdiff_1.1.5_linux_amd64.tar.gz | tar -xz dbdiff sudo mv dbdiff /usr/local/bin/ ``` diff --git a/cmd/compare.go b/cmd/compare.go index cd72a66..c36d6c1 100644 --- a/cmd/compare.go +++ b/cmd/compare.go @@ -93,7 +93,7 @@ var CompareCmd = &cobra.Command{ if err := output.WriteFile(cfg.Output, outputStr); err != nil { return fmt.Errorf("failed to write output: %w", err) } - logging.Info(fmt.Sprintf("Output written to: %s", cfg.Output)) + logging.Info(fmt.Sprintf("Output written to: %s", dsn.Redact(cfg.Output))) } return nil diff --git a/cmd/interactive.go b/cmd/interactive.go index 7a733a0..fa36e73 100644 --- a/cmd/interactive.go +++ b/cmd/interactive.go @@ -7,6 +7,7 @@ import ( tea "github.com/charmbracelet/bubbletea" "github.com/meru143/dbdiff/internal/db" + "github.com/meru143/dbdiff/internal/db/dsn" "github.com/meru143/dbdiff/internal/diff" "github.com/meru143/dbdiff/internal/logging" "github.com/meru143/dbdiff/internal/output" @@ -130,7 +131,7 @@ var InteractiveCmd = &cobra.Command{ return fmt.Errorf("failed to save interactive migration: %w", err) } - fmt.Printf("\nSelected migration output stored securely to: %s\n", cfg.Output) + fmt.Printf("\nSelected migration output stored securely to: %s\n", dsn.Redact(cfg.Output)) return nil }, } diff --git a/cmd/migrate.go b/cmd/migrate.go index 48c140d..c266348 100644 --- a/cmd/migrate.go +++ b/cmd/migrate.go @@ -153,7 +153,7 @@ var MigrateCmd = &cobra.Command{ // Confirmation prompt (only for non-dry-run, non-force) if !cfg.DryRun && !cfg.Force && cfg.Output != "stdout" { - fmt.Printf("\nMigration will write to: %s\n", cfg.Output) + fmt.Printf("\nMigration will write to: %s\n", dsn.Redact(cfg.Output)) if !confirmPrompt() { logging.Info("Migration cancelled") return nil @@ -169,9 +169,10 @@ var MigrateCmd = &cobra.Command{ existingContent, _ := os.ReadFile(cfg.Output) backupPath, err := backupMgr.Backup("migration", existingContent) if err != nil { - logging.Warn(fmt.Sprintf("Failed to create backup: %v", err)) + // --backup-dir, like -o, may hold a URL, which the path and the error echo. + logging.Warn(fmt.Sprintf("Failed to create backup: %v", dsn.Redact(err.Error()))) } else { - logging.Info(fmt.Sprintf("Backup created: %s", backupPath)) + logging.Info(fmt.Sprintf("Backup created: %s", dsn.Redact(backupPath))) } } } @@ -182,7 +183,7 @@ var MigrateCmd = &cobra.Command{ if err := output.WriteFile(cfg.Output, fullSQL); err != nil { return fmt.Errorf("failed to write migration: %w", err) } - logging.Info(fmt.Sprintf("Migration written to: %s", cfg.Output)) + logging.Info(fmt.Sprintf("Migration written to: %s", dsn.Redact(cfg.Output))) } return nil diff --git a/cmd/tables.go b/cmd/tables.go index cd5950d..66437e3 100644 --- a/cmd/tables.go +++ b/cmd/tables.go @@ -47,7 +47,7 @@ var TablesCmd = &cobra.Command{ } if len(tables) == 0 { - fmt.Printf("No tables found in schema: %s\n", cfg.Schema) + fmt.Printf("No tables found in schema: %s\n", dsn.Redact(cfg.Schema)) return nil } diff --git a/internal/config/config.go b/internal/config/config.go index 57f2c68..783e656 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -2,8 +2,10 @@ package config import ( "fmt" + "strings" "time" + "github.com/meru143/dbdiff/internal/db/dsn" "github.com/spf13/viper" ) @@ -57,6 +59,11 @@ func Load(flags map[string]interface{}) (*Config, error) { } if configFile, ok := flags["config"].(string); ok && configFile != "" { + // viper takes what follows a path's last '.' for the file's type, and its error quotes + // that: in a URL, part of the password (Unsupported Config Type "word@host:5432"). + if strings.Contains(configFile, "://") { + return nil, fmt.Errorf("failed to read config file: --config takes a file, not a URL: %s", dsn.Redact(configFile)) + } v.SetConfigFile(configFile) if err := v.ReadInConfig(); err != nil { return nil, fmt.Errorf("failed to read config file: %w", err) diff --git a/internal/config/config_test.go b/internal/config/config_test.go index a7496d3..7929f9c 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -2,6 +2,7 @@ package config import ( "os" + "strings" "testing" "time" ) @@ -128,6 +129,15 @@ schema: testschema } } +// A URL given for --config isn't read: viper takes what follows its last '.' for the file's +// type, and quoted that in its error (Unsupported Config Type "QZYb@localhost:5432"). +func TestLoad_ConfigURL(t *testing.T) { + _, err := Load(map[string]interface{}{"config": "postgres://app:QZXa.QZYb@localhost:5432"}) + if err == nil || strings.Contains(err.Error(), "QZ") || !strings.Contains(err.Error(), "postgres://app:***@localhost:5432") { + t.Errorf("expected an error naming the URL without its password, got %v", err) + } +} + func TestLoad_IgnorePatterns(t *testing.T) { flags := map[string]interface{}{ "ignore-patterns": []string{"*_created_at", "*_updated_at"}, diff --git a/internal/db/dsn/redact.go b/internal/db/dsn/redact.go index 4935b63..d7c843a 100644 --- a/internal/db/dsn/redact.go +++ b/internal/db/dsn/redact.go @@ -10,12 +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. +// 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: CheckPassword reads values so. Redact ends +// a password-like value nowhere, and hides it with all that follows it (toEnd): a driver +// reads ?password=P&Q as the password P and a parameter Q, but Q may be the rest of the +// password the user meant, and neither the driver nor Redact can tell. const ( - inQuery = "&" - inSettings = "&;" + inQuery = "&" + toEnd = "" ) // dsnAddr matches what follows the '@' of a go-sql-driver DSN: a network with its address @@ -30,8 +32,8 @@ 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. If that '@' is in the -// value of a password parameter, as in host:1433?password=p@ss, the rest of the value is +// malformed URL; that can hide more than the password, never less. If that '@' follows the +// '=' of a password parameter, as in host:1433?password=p@ss, all that follows the ':' 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 @@ -39,20 +41,21 @@ var dsnAddr = regexp.MustCompile(`^([A-Za-z0-9]+\([^)]*\))?/`) // 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. +// password-like parameter (see secretValues) is hidden wherever it is, before any quote in +// it is read, and so is all that follows it, to the end of s or of the quotes around it +// (see toEnd): postgres://host/db?sslmode=disable&password=***. // // 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) + return redactOne(s, toEnd) } var b strings.Builder quoted := false text, key := 0, 0 // where the text not yet written, and the name before the next '=', start flush := func(end int) { - b.WriteString(redactOne(s[text:end])) + b.WriteString(redactOne(s[text:end], toEnd)) text = end } starts := schemeStarts(s) @@ -69,7 +72,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:], inSettings); n > 0 { + if n := valueLen(s[v:], toEnd); n > 0 { b.WriteString(mask) text = v + n } @@ -91,46 +94,51 @@ func Redact(s string) string { continue case len(starts) > 0 && starts[0] == i: flush(i) - b.WriteString(redactOne(s[i:])) + b.WriteString(redactOne(s[i:], toEnd)) return b.String() } i++ } if !quoted { - return redactOne(s) + return redactOne(s, toEnd) } flush(len(s)) return b.String() } +// RedactToSeparator hides the password in connStr, a single connection URL, like Redact, but +// ends a password parameter's value at the next '&', the way a driver reads it, keeping the +// parameters after it instead of hiding them. connectOnce re-parses the result: a parameter +// the driver rejects still reports what is wrong with it, while the password is gone. +func RedactToSeparator(connStr string) string { + return redactOne(connStr, inQuery) +} + // redactOne hides the secrets of one connection string: the password between the first -// ':' 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 { +// ':' after the scheme and the last '@' (see passwordEnd), and the value of a password-like +// parameter with all that follows it. +func redactOne(t, ends string) string { n := schemeLen(t) head, rest := t[:n], t[n:] if colon := userinfo(rest, n > 0); colon > 0 { - rest = rest[:colon] + mask + rest[passwordEnd(rest, strings.LastIndexByte(rest, '@')):] + rest = rest[:colon] + mask + rest[passwordEnd(rest, strings.LastIndexByte(rest, '@'), ends):] } 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 redactParams(rest, inSettings) + return head + redactParams(rest, ends) } // 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 { +// host:1433?password=p@ss, where it starts no host; ends says what ends that value (see +// valueLen). 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, ends string) int { q := strings.IndexByte(rest, '?') if q < 0 || q > at { return at } - for _, v := range secretValues(rest[q:], inQuery) { + for _, v := range secretValues(rest[q:], ends) { if q+v[0] <= at && at < q+v[1] { return len(rest) } @@ -207,7 +215,7 @@ func CheckPassword(connStr string) error { at := strings.LastIndexByte(rest, '@') end := at if colon > 0 { - end = passwordEnd(rest, at) + end = passwordEnd(rest, at, inQuery) } var ambiguous bool var fix string @@ -227,6 +235,18 @@ func CheckPassword(connStr string) error { 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://": + // go-sql-driver has no password parameter: it sends an unknown one, password among + // them, to the server as a SET, where it never logs anyone in and, for an account with + // no password, the server's syntax error quotes its value (and with a quoted value it + // would run SET password on the logged-in account). So refuse one outright. Scan from + // the first '?', not after the last '@', which an '@' in a query value moves past; a + // '?' inside a userinfo password only reaches a value whose '@' then makes the URL + // ambiguous and refused below anyway, so this never wrongly refuses a connectable URL. + if q := strings.IndexByte(rest, '?'); q >= 0 && len(secretValues(rest[q:], inQuery)) > 0 { + // No URL in the message: embedding one with tcp(host)/db would trip the scheme-less + // DSN heuristic when main redacts the error again. The user knows their own URL. + return fmt.Errorf("a MySQL password must be in the user info of the URL, not a query parameter; a password query parameter is sent to the server as a SET and never logs in") + } fix = "end it with /database after the address, and percent-encode any '@' after that '/'" ambiguous = colon > 0 && (end != at || !strings.Contains(rest[at:], "/")) } @@ -238,7 +258,158 @@ func CheckPassword(connStr string) error { 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). +// tokenSeps separate the names and values of a query or settings string: '&' +// between parameters, ';' and ',' in settings and host lists, '=' before a +// value, and the whitespace a '%'-escape can decode to. A driver or server +// quotes a token bounded by these, so what it hides is compared token by token. +const tokenSeps = "&=;, \t\r\n" + +// isTokenSep reports whether r is one of tokenSeps. +func isTokenSep(r rune) bool { + return r < 128 && strings.IndexByte(tokenSeps, byte(r)) >= 0 +} + +// tokens lowercases s and splits it on tokenSeps, dropping empty fields. +func tokens(s string) []string { + return strings.FieldsFunc(strings.ToLower(s), isTokenSep) +} + +// hiddenRegion returns the tokens of what Redact hides after the '=' of the +// first password parameter in connStr's query: each raw piece between +// tokenSeps, and what it decodes to both ways (url.PathUnescape, as pgx and +// net/url read it, and url.QueryUnescape, as go-sql-driver and go-mssqldb do, +// where '+' is a space), all split into tokens. Each piece is decoded on its +// own and before it is lowercased, as the drivers decode each parameter's raw +// bytes: a bad escape in one (a password of 50%off) leaves the others decoded, +// and a raw byte still joins the bytes an escape beside it decodes to (%C3 and +// a raw 0xA9 are é). ok is false when the query holds no password parameter. +func hiddenRegion(connStr string) (region map[string]struct{}, ok bool) { + n := schemeLen(connStr) + q := strings.IndexByte(connStr[n:], '?') + if n == 0 || q < 0 { + return nil, false + } + secrets := secretValues(connStr[n+q:], toEnd) + if len(secrets) == 0 { + return nil, false + } + region = map[string]struct{}{} + for _, p := range strings.FieldsFunc(connStr[n+q+secrets[0][0]:], isTokenSep) { + forms := []string{p} + if d, err := url.PathUnescape(p); err == nil { + forms = append(forms, d) + } + if d, err := url.QueryUnescape(p); err == nil { + forms = append(forms, d) + } + for _, f := range forms { + for _, t := range tokens(f) { + region[t] = struct{}{} + } + } + } + return region, true +} + +// HasPasswordParam reports whether connStr's query holds a password parameter, whose value a +// driver ends at the next '&' while Redact hides all that follows its '='. +func HasPasswordParam(connStr string) bool { + _, ok := hiddenRegion(connStr) + return ok +} + +// HideParams returns err, the error for connecting with connStr, unless it quotes a token of +// what Redact hides after the '=' of the first password parameter in connStr's query. A +// driver reads password=pass&word=x as the password pass and a parameter word, and can quote +// that parameter, or the server it sends it to, when it refuses it (unrecognized +// configuration parameter "word"), but word may be the rest of the password. The server or +// driver may pad a name with the spaces, tabs or control bytes a '%'-escape decoded to +// (parameter "word "), hold a setting name inside an options value, or turn a '+' into a +// space, so each token of each quoted string in the error is tested for equality, at any +// length, against a token of the region (raw and decoded both ways), not matched parameter by +// parameter. go-mssqldb names a duplicated key without quotes (key word provided more than +// once), so the tokens between "key " and " provided more than once" are tested too. Matching +// whole tokens, not substrings, keeps an ordinary error that merely contains the user or +// database name: password authentication failed, and database "db" does not exist, pass +// through. Then HideParams returns an error that names connStr redacted. +func HideParams(connStr string, err error) error { + if err == nil { + return err + } + region, ok := hiddenRegion(connStr) + if !ok { + return err + } + inRegion := func(s string) bool { + for _, t := range tokens(s) { + if _, ok := region[t]; ok { + return true + } + } + return false + } + hidden := false + for _, tok := range quotedTokens(err.Error()) { + hidden = hidden || inRegion(tok) + } + if _, after, ok := strings.Cut(err.Error(), "key "); ok { + if name, _, ok := strings.Cut(after, " provided more than once"); ok { + hidden = hidden || inRegion(name) + } + } + // A quote inside a token breaks the pairing above (parameter "a"b" yields a), so a token + // that holds one is searched for whole. + msg := strings.ToLower(err.Error()) + for t := range region { + hidden = hidden || strings.ContainsAny(t, `"'`) && hasWord(msg, t) + } + if hidden { + return fmt.Errorf("connecting with %q failed with an error that quotes part of what follows the '=' of its password parameter, which may be part of the password, so the error is left out: put the password after the user name, or write an '&' in it as %%26", Redact(connStr)) + } + return err +} + +// hasWord reports whether the token t occurs whole in the lowercase message s: bounded on each +// side by an end, whitespace or a separator, or the punctuation messages wrap a value in +// (quotes, parentheses, a trailing colon). t may hold that punctuation itself (parameter +// "a"b"), so it is searched for as it is, not split up. +func hasWord(s, t string) bool { + if t == "" { + return false + } + edge := func(i int) bool { + return i < 0 || i >= len(s) || strings.IndexByte(tokenSeps+":()[]{}\"'`", s[i]) >= 0 + } + for from := 0; ; { + i := strings.Index(s[from:], t) + if i < 0 { + return false + } + i += from + if edge(i-1) && edge(i+len(t)) { + return true + } + from = i + 1 + } +} + +// quotedTokens returns the text inside each "..." and '...' pair in s, left to right within +// each quote kind. An unpaired final quote starts no token: the loop stops before the last +// field, which Split puts whatever follows the final quote into. +func quotedTokens(s string) []string { + var toks []string + for _, q := range []string{`"`, "'"} { + parts := strings.Split(s, q) + for i := 1; i < len(parts)-1; i += 2 { + toks = append(toks, parts[i]) + } + } + return toks +} + +// redactParams hides the value of each password-like parameter in t (see secretValues), +// each ending at a byte of ends: with toEnd the first value runs to the end of t, so all that +// follows a password parameter is hidden; with inQuery each value ends at the next '&'. func redactParams(t, ends string) string { var b strings.Builder written := 0 @@ -254,9 +425,9 @@ func redactParams(t, ends string) 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). +// ends, in a URL's query (?password=x&...) or in settings (user id=sa;password=x), a value +// ending at a byte of ends (see valueLen): 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 diff --git a/internal/db/dsn/redact_test.go b/internal/db/dsn/redact_test.go index 7359798..d0a59d0 100644 --- a/internal/db/dsn/redact_test.go +++ b/internal/db/dsn/redact_test.go @@ -1,7 +1,9 @@ package dsn import ( + "errors" "net/url" + "reflect" "strings" "testing" "time" @@ -32,17 +34,27 @@ func TestRedact(t *testing.T) { {"user with @, as on Azure", "postgres://admin@server:s3cret@host/app", "postgres://admin@server:***@host/app"}, {"empty user", "postgres://:s3cret@host/app", "postgres://:***@host/app"}, - // without a scheme: go-sql-driver's DSN, and semicolon-separated settings + // without a scheme: go-sql-driver's DSN, and semicolon-separated settings, whose password + // is hidden with all that follows it, as in a URL {"DSN without a scheme", "root:s3cret@tcp(localhost:3306)/app", "root:***@tcp(localhost:3306)/app"}, {"DSN with a space in the password", "root:my s3cret@tcp(host)/app", "root:***@tcp(host)/app"}, {"DSN with quote pairs in the password", "root:a\"s3\"c`r`et@tcp(host)/app", "root:***@tcp(host)/app"}, - {"settings", "server=host;user id=sa;password=s3cret;database=app", "server=host;user id=sa;password=***;database=app"}, - {"settings with a quoted password", `server=host;pwd="s3c;ret";database=app`, "server=host;pwd=***;database=app"}, - {"settings with quotes in a password", `server=host;password=a"s3"c` + "`r`" + `et;database=app`, "server=host;password=***;database=app"}, + {"settings", "server=host;user id=sa;password=s3cret;database=app", "server=host;user id=sa;password=***"}, + {"settings with a quoted password", `server=host;pwd="s3c;ret";database=app`, "server=host;pwd=***"}, + {"settings with quotes in a password", `server=host;password=a"s3"c` + "`r`" + `et;database=app`, "server=host;password=***"}, {"settings in text, password quoted", `failed with server=host;pwd="s3cret";database=app here`, - `failed with server=host;pwd=***;database=app here`}, + `failed with server=host;pwd=***`}, {"settings in text, quotes in a braced password", `failed with server=host;pwd={a"s3cret"c};database=app`, - `failed with server=host;pwd=***;database=app`}, + `failed with server=host;pwd=***`}, + // go-mssqldb reads password=P&Q in settings as the password P&Q, and pgx in keyword/value + // ones; go-sql-driver reads a DSN's parameters as a URL's. + {"'&' in a password setting", "server=host;password=s3cret&s3cret;database=app", "server=host;password=***"}, + {"'&' in a keyword/value password", "host=db password=s3cret&s3cret dbname=app", "host=db password=***"}, + {"'&' in a DSN's password parameter", "root@tcp(host:3306)/app?password=s3cret&s3cret", "root@tcp(host:3306)/app?password=***"}, + {"'&' in a password parameter in prose", "failed: ?sslmode=disable&password=s3cret&s3cret here", + "failed: ?sslmode=disable&password=***"}, + {"'&' in quoted settings", `unknown command "server=host;password=s3cret&s3cret" for "dbdiff"`, + `unknown command "server=host;password=***" for "dbdiff"`}, {"URL inside quoted prose", `error: "connecting to postgres://user:s3cret@host/db failed"`, `error: "connecting to postgres://user:***@host/db failed"`}, @@ -70,28 +82,53 @@ func TestRedact(t *testing.T) { {"password parameter", "postgres://user@host/app?sslmode=disable&password=s3cret", "postgres://user@host/app?sslmode=disable&password=***"}, {"pwd parameter, any case", "sqlserver://host?database=app&PWD=s3cret&encrypt=disable", - "sqlserver://host?database=app&PWD=***&encrypt=disable"}, + "sqlserver://host?database=app&PWD=***"}, {"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. + // A driver reads ?password=P&Q as the password P and a parameter Q, but Q may be the rest of + // the password: a password parameter's value is hidden with all that follows it, to the + // end of the URL or of the quotes around it. + {"'&' in a password parameter", "postgres://app@host/db?password=s3cret&s3cret", "postgres://app@host/db?password=***"}, + {"'&' in a password parameter after another", "postgres://app@host:5432/db?sslmode=disable&password=s3cret&s3cret", + "postgres://app@host:5432/db?sslmode=disable&password=***"}, + {"'&' and two '=' in a password parameter", "postgres://app@host/db?password=s3cret&a=b=s3cret", "postgres://app@host/db?password=***"}, + {"'&' and '=' in a password parameter", "postgres://app@host/db?password=s3cret&s3cret=s3cret", "postgres://app@host/db?password=***"}, + {"'&' in sslpassword", "postgres://app@host/db?sslpassword=k3y&k3y", "postgres://app@host/db?sslpassword=***"}, + {"'&' in sslpassword after another", "postgres://app:s3cret@host:5432/db?sslmode=disable&sslpassword=k3y&k3y", + "postgres://app:***@host:5432/db?sslmode=disable&sslpassword=***"}, + {"'&' and two '=' in sslpassword", "postgres://app@host/db?sslpassword=k3y&a=b=k3y", "postgres://app@host/db?sslpassword=***"}, + {"'&' and '=' in sslpassword", "postgres://app@host/db?sslpassword=k3y&k3y=k3y", "postgres://app@host/db?sslpassword=***"}, + {"'&' in a SQL Server password parameter", "sqlserver://host?database=db&password=s3cret&s3cret", + "sqlserver://host?database=db&password=***"}, + {"'&' in a MySQL password parameter", "mysql://root@tcp(host:3306)/db?password=s3cret&s3cret", + "mysql://root@tcp(host:3306)/db?password=***"}, + {"'&' then '@' in a password parameter, after a port", "postgres://app@host:5432/db?password=s3cret&s3cret@s3cret", + "postgres://app@host:***"}, + {"'&' then '@' in a password parameter, after a password", "postgres://app:s3cret@host/db?password=s3cret&s3cret@s3cret", + "postgres://app:***"}, + {"'&' in a password parameter, in double quotes", `invalid argument "postgres://app@host/db?password=s3cret&s3cret" for "--timeout" flag`, + `invalid argument "postgres://app@host/db?password=***" for "--timeout" flag`}, + {"'&' in a password parameter, in pgx's backticks", + "cannot parse `postgres://app@host/db?sslmode=bogus&password=xxxxx&s3cret=s3cret`: failed to configure TLS (sslmode is invalid)", + "cannot parse `postgres://app@host/db?sslmode=bogus&password=***`: failed to configure TLS (sslmode is invalid)"}, + {"'&' in a password parameter, in prose", "connecting to postgres://app@host/db?password=s3cret&s3cret failed: timeout", + "connecting to postgres://app@host/db?password=***"}, {"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=***"}, {"';' 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 + "postgres://app@host/db?password=***"}, {"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 with spaces", "sqlserver://host?password=my s3cret&database=app", "sqlserver://host?password=***"}, {"value in braces", "sqlserver://host?odbc=uid=sa;pwd={a&b}}c}&database=app", - "sqlserver://host?odbc=uid=sa;pwd=***&database=app"}, + "sqlserver://host?odbc=uid=sa;pwd=***"}, {"value in quotes", "sqlserver://host?odbc=uid=sa;pwd='a&b''c'&database=app", - "sqlserver://host?odbc=uid=sa;pwd=***&database=app"}, + "sqlserver://host?odbc=uid=sa;pwd=***"}, {"text after the closing brace", "sqlserver://host?odbc=pwd={a&b}s3cret&database=app", - "sqlserver://host?odbc=pwd=***&database=app"}, + "sqlserver://host?odbc=pwd=***"}, {"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. + "postgres://app@host/db?pass%77ord=***"}, + // 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=***"}, @@ -143,11 +180,31 @@ func TestRedact(t *testing.T) { } } +// RedactToSeparator hides the password but ends a password parameter's value at the next '&', +// keeping the parameters after it, so connectOnce can re-parse a URL that failed and still +// learn what is wrong with a later parameter. A raw '&' tail stays in the re-parsed copy; +// connectOnce shows pgx's reason only when it names no token of that tail, and otherwise +// gives the hint (see TestConnectParseErrorHidesPasswordParameter and ...HintsOnParamValue). +func TestRedactToSeparator(t *testing.T) { + for _, tt := range []struct{ in, want string }{ + {"postgres://app@host/db?password=s3cret&sslmode=disabled", "postgres://app@host/db?password=***&sslmode=disabled"}, + {"postgres://app@host/db?sslmode=disabled&password=s3cret", "postgres://app@host/db?sslmode=disabled&password=***"}, + {"postgres://app@host/db?password=s3cret&tail", "postgres://app@host/db?password=***&tail"}, + {"postgres://app:s3cret@host/db?connect_timeout=ten", "postgres://app:***@host/db?connect_timeout=ten"}, + {"postgres://app@host/db?sslmode=disable", "postgres://app@host/db?sslmode=disable"}, + } { + if got := RedactToSeparator(tt.in); got != tt.want { + t.Errorf("RedactToSeparator(%q) = %q, want %q", tt.in, got, tt.want) + } + } +} + // Any password is hidden whole, whatever it holds: in a URL's userinfo, in a DSN without a // 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", "a?pwd=b"} { + 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", + "s3&cret", "a&b=c=d", "a&b@c:d"} { f.Add("app", p) } f.Fuzz(func(t *testing.T, user, pass string) { @@ -157,8 +214,15 @@ func FuzzRedactPassword(f *testing.F) { t.Skip() } cases := map[string]string{ - "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", + "server=host;user id=" + user + ";password={" + strings.ReplaceAll(pass, "}", "}}") + "};database=db": "server=host;user id=" + user + ";password=***", + "postgres://" + user + "@host/db?pass%77ord=" + url.QueryEscape(pass) + "&sslmode=disable": "postgres://" + user + "@host/db?pass%77ord=***", + } + // A password parameter written raw, '&', '@' and quotes included, is hidden to the end + // (the spaces after its '=' stay). + if strings.TrimLeft(pass, " \t") == pass { + cases["postgres://"+user+"@host/db?sslmode=disable&password="+pass] = "postgres://" + user + "@host/db?sslmode=disable&password=***" + cases["sqlserver://host?database=db&password="+pass] = "sqlserver://host?database=db&password=***" + cases["server=host;user id="+user+";password="+pass] = "server=host;user id=" + user + ";password=***" } 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"} { @@ -176,9 +240,60 @@ func FuzzRedactPassword(f *testing.F) { }) } +// FuzzHideParams checks that an error quoting any whole parameter name in what follows a +// password parameter is hidden, at any length (regress and leaks finding 1), and that +// HideParams never panics on an arbitrary error. +// hiddenRegion decodes piece by piece, yet must hold every token of the whole tail decoded at +// once, as a driver reads it, raw bytes beside escapes included. +func FuzzHiddenRegion(f *testing.F) { + for _, s := range []string{"9a", "a%26b", "Kq7%C3\xa9Wn=1", "\xd1%80", "x+y", "50%off&k3y"} { + f.Add(s) + } + f.Fuzz(func(t *testing.T, tail string) { + region, ok := hiddenRegion("postgres://app@host/db?password=Secret9&" + tail) + if !ok { + t.Fatal("no region for a password parameter") + } + for _, unescape := range []func(string) (string, error){url.PathUnescape, url.QueryUnescape} { + d, err := unescape("Secret9&" + tail) + if err != nil { + continue + } + for _, tok := range tokens(d) { + if _, in := region[tok]; !in { + t.Errorf("tail %q: token %q of the decoded tail is missing", tail, tok) + } + } + } + }) +} + +func FuzzHideParams(f *testing.F) { + for _, s := range []string{"9a", "Q", "ab", "k3y", "owner:ops", "a&b", "x=y", "a;b", `a"b`, `"ab`, `ab"`} { + f.Add(s) + } + f.Fuzz(func(t *testing.T, tail string) { + connStr := "postgres://app@host/db?sslmode=disable&password=Secret9&" + tail + HideParams(connStr, errors.New("connection refused")) // crash-only, arbitrary tail + if strings.ContainsAny(tail, "\x00#?%+") { + return // keep raw == decoded + } + for _, seg := range strings.FieldsFunc(tail, func(r rune) bool { return r == '&' || r == ';' }) { + name := strings.SplitN(seg, "=", 2)[0] // the server quotes the name verbatim + if len(tokens(name)) == 0 { + continue + } + err := errors.New(`unrecognized configuration parameter "` + name + `" (SQLSTATE 42704)`) + if HideParams(connStr, err) == err { + t.Errorf("tail %q: a quoted name %q was not hidden", tail, name) + } + } + }) +} + // 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. +// hides in its userinfo, 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 @@ -209,7 +324,14 @@ func TestCheckPassword(t *testing.T) { {"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}, + // A MySQL password parameter is refused by its own rule (see TestCheckPasswordMySQLParam), + // without the URL; the raw-'&' MySQL cases below moved there too. + // As before, CheckPassword reads a password parameter's value up to the next '&', as the + // drivers do. Its error hides all after the '=', as Redact does. + {"postgres://app@host:5432/db?sslmode=disable&password=s3cret&s3cret", true}, + {"sqlserver://host?database=db&password=s3cret&s3cret", true}, + {"postgres://app@host:5432/db?password=s3cret&s3cret@s3cret", false}, + {"sqlserver://host:1433?database=db&password=s3cret&s3cret@s3cret", false}, } { err := CheckPassword(tt.url) if tt.ok != (err == nil) || err != nil && (strings.Contains(err.Error(), "s3cret") || !strings.Contains(err.Error(), "***")) { @@ -222,9 +344,47 @@ func TestCheckPassword(t *testing.T) { } } +// go-sql-driver has no password parameter: it sends one to the server as a SET, which never +// logs in (and would run SET password on a quoted value), so a MySQL URL carrying one is +// refused whatever follows it — a second parameter or a value over 80 characters included, +// where the server's error used to echo part of it. The refusal names no URL, so nothing +// leaks and Redact leaves it as it is. +func TestCheckPasswordMySQLParam(t *testing.T) { + for _, u := range []string{ + "mysql://root@tcp(host:3306)/db?password=s3cret", + "mysql://root@tcp(host:3306)/db?sql_mode=ANSI&password=s3cret", + "mysql+tcp://root@tcp(host:3306)/db?password=s3cret&x=y", + "mysql://root@tcp(host:3306)/db?Pwd=s3cret&z", + "mysql://root@tcp(host:3306)/db?password=" + strings.Repeat("s3cret", 16), // over 80 characters + "mysql://root@tcp(host:3306)/db?password=p@ss", // an '@' in the value + "mysql://root@tcp(host:3306)/db?password=s3cret@s3cret&x=/", // '@' in the value, then a '/' + "mysql://root@tcp(host:3306)/db?password=s3cret&s3cret@s3cret", // raw '&', then '@' + "mysql://root@tcp(host:3306)/db?connectionAttributes=a@b/c&password=s3cret", // an '@' in an earlier value moves the last '@' past the query + } { + err := CheckPassword(u) + if err == nil || strings.Contains(err.Error(), "s3cret") { + t.Errorf("CheckPassword(%q) = %v, want a refusal without the password", u, err) + } + if msg := "Error: failed to initialize driver: " + err.Error(); Redact(msg) != msg { + t.Errorf("CheckPassword(%q): Redact changes its error to %q", u, Redact(msg)) + } + } + // A non-password query parameter, and a password in the user info, still connect. + for _, u := range []string{ + "mysql://root:s3cret@tcp(host:3306)/db?parseTime=true", + "mysql://root@tcp(host:3306)/db?charset=utf8mb4&parseTime=true", + "mysql://root:s3cret@tcp(host:3306)/db?connectionAttributes=owner:ops%40example", + } { + if err := CheckPassword(u); err != nil { + t.Errorf("CheckPassword(%q) = %v, want nil", u, err) + } + } +} + // 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). +// does, reads as the password all that CheckPassword takes for it, or fails (go test -fuzz +// FuzzCheckPassword explores beyond these seeds). Redact hides that, and all that follows a +// password parameter's '=' too. 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"}, @@ -239,7 +399,7 @@ func FuzzCheckPassword(f *testing.F) { continue } at := strings.LastIndexByte(rest, '@') - hidden := rest[strings.IndexByte(rest[:at], ':')+1 : passwordEnd(rest, at)] + hidden := rest[strings.IndexByte(rest[:at], ':')+1 : passwordEnd(rest, at, inQuery)] var got, want string switch scheme { case "postgres://": @@ -276,6 +436,95 @@ func FuzzCheckPassword(f *testing.F) { }) } +// A driver reads what follows an '&' in a password parameter's value as parameters, and its +// error, or the server's, can quote one of them: HideParams leaves such an error out, and +// keeps the others. The errors are the ones PostgreSQL 16, go-mssqldb and MySQL 8.0 give. +func TestHideParams(t *testing.T) { + const pgConnect = "failed to ping: failed to connect to `user=app database=db`: 127.0.0.1:5432 (127.0.0.1): server error: FATAL: " + for _, tt := range []struct { + url, err string + hidden bool + }{ + {"postgres://app@host/db?password=s3cret&K3y=x", pgConnect + `unrecognized configuration parameter "K3y" (SQLSTATE 42704)`, true}, + {"postgres://app:s3cret@host/db?sslmode=disable&sslpassword=s3cret&k3y=x", pgConnect + `unrecognized configuration parameter "k3y" (SQLSTATE 42704)`, true}, + {"postgres://app@host/db?password=s3cret&statement_timeout=k3y", pgConnect + `invalid value for parameter "statement_timeout": "k3y" (SQLSTATE 22023)`, true}, + {"postgres://app@host/db?password=s3cret&k%33y=x", pgConnect + `unrecognized configuration parameter "k3y" (SQLSTATE 42704)`, true}, + {"sqlserver://host?database=db&password=s3cret&log=k3y", `invalid log parameter 'k3y': strconv.ParseUint: parsing "k3y": invalid syntax`, true}, + {"mysql://app@tcp(host:3306)/db?password=s3cret", "Error 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds " + + "to your MySQL server version for the right syntax to use near 's3cret' at line 1", true}, + // A '%'-escape in a name after the '&' decodes to a space, tab or control byte the + // server keeps inside the quotes it prints, or an options value carries the setting + // name; the region still matches the quoted token after a trim. go-mssqldb names a + // duplicated key without quotes. + {"postgres://app@host/db?password=s3cret&k3y%20=x", pgConnect + `unrecognized configuration parameter "k3y " (SQLSTATE 42704)`, true}, + {"postgres://app@host/db?sslmode=disable&password=s3cret&%20k3y=x", pgConnect + `unrecognized configuration parameter " k3y" (SQLSTATE 42704)`, true}, + {"postgres://app@host/db?password=s3cret&k3y%0D=x", pgConnect + "unrecognized configuration parameter \"k3y\r\" (SQLSTATE 42704)", true}, + {"postgres://app@host/db?password=s3cret&options=-c%20k3y%3D1", pgConnect + `unrecognized configuration parameter "k3y" (SQLSTATE 42704)`, true}, + {"sqlserver://host?database=db&password=s3cret&k3y&k3y", "key k3y provided more than once", true}, + // A 1-2 character piece after a raw '&' must be hidden too, at any length (regress and + // leaks finding 1). pgx's parse quote, PostgreSQL's server quote, SQL Server's quoted + // value and go-mssqldb's unquoted duplicate key all name it. + {"postgres://app@host/db?sslmode=disable&password=s3cret&9a", `failed to parse as URL (missing key/value separator "=" in URI query parameter: "9a")`, true}, + {"postgres://app@host/db?password=s3cret&Q", `missing key/value separator "=" in URI query parameter: "Q"`, true}, + {"postgres://app@host/db?password=s3cret&ab=c=d", `extra key/value separator "=" in URI query parameter: "ab"`, true}, + {"postgres://app@host/db?password=s3cret&ab", pgConnect + `unrecognized configuration parameter "ab" (SQLSTATE 42704)`, true}, + {"sqlserver://host?database=db&password=s3cret&log=ab", `invalid log parameter 'ab': strconv.ParseUint: parsing "ab": invalid syntax`, true}, + {"sqlserver://host?database=db&password=s3cret&Qz&Qz", "key Qz provided more than once", true}, + // go-mssqldb reads the query with QueryUnescape, so a '+' in the tail is a space; the + // region, decoded that way too, still matches it (regress finding 5). + {"sqlserver://host?database=db&password=s3cret&log=Zq+rB", `invalid log parameter 'Zq rB': strconv.ParseUint: parsing "Zq rB": invalid syntax`, true}, + {"sqlserver://host?database=db&password=s3cret&a+Zq&a+Zq", "key a Zq provided more than once", true}, + // A quote inside a name or value breaks the quote pairing, so the token that holds it + // is searched for whole in the error. + {`postgres://app@host/db?password=s3cret&Zq"Zx=1`, pgConnect + `unrecognized configuration parameter "Zq"Zx" (SQLSTATE 42704)`, true}, + {`postgres://app@host/db?password=s3cret&"Zq9=1`, pgConnect + `unrecognized configuration parameter ""Zq9" (SQLSTATE 42704)`, true}, + {"postgres://app@host/db?password=s3cret&Zq%22Zy=1", pgConnect + `unrecognized configuration parameter "Zq"Zy" (SQLSTATE 42704)`, true}, + {"sqlserver://host?database=db&password=s3cret&log=Zq'Zz", `invalid log parameter 'Zq'Zz': strconv.ParseUint: parsing "Zq'Zz": invalid syntax`, true}, + // A bad escape in the password leaves the later pieces decoded, as the drivers decode + // each parameter on its own. + {"sqlserver://host?database=db&password=50%off&log=Zq%28Zz", `invalid log parameter 'Zq(Zz': strconv.ParseUint: parsing "Zq(Zz": invalid syntax`, true}, + // An escape and a raw byte beside it decode to one character (%C3 and 0xA9 are é). + {"postgres://app@host/db?password=s3cret&Kq7%C3\xa9Wn=1", pgConnect + `unrecognized configuration parameter "Kq7éWn" (SQLSTATE 42704)`, true}, + {"sqlserver://host?database=db&password=s3cret&log=Zq%C3\xa9Zz", `invalid log parameter 'ZqéZz': strconv.ParseUint: parsing "ZqéZz": invalid syntax`, true}, + {"postgres://app@host/db?password=s3cret&sslmode=disable", pgConnect + `password authentication failed for user "app" (SQLSTATE 28P01)`, false}, + {"postgres://app:s3cret@host/db?sslmode=disable", pgConnect + `database "db" does not exist (SQLSTATE 3D000)`, false}, + {"sqlserver://host?database=db&password=s3cret&k3y", "login error: mssql: Login failed for user 'app'.", false}, + // A whole-token match keeps an ordinary error that only contains the user or database + // name inside the password value or a later value (regress finding 3): a wrong password + // that starts with the user name, and an application_name that starts with the database. + {"postgres://bob@host/db?password=bobZx9", `password authentication failed for user "bob" (SQLSTATE 28P01)`, false}, + {"postgres://app@host/nodb?password=Zx9pw&application_name=nodb-ci", `database "nodb" does not exist (SQLSTATE 3D000)`, false}, + } { + in := errors.New(tt.err) + got := HideParams(tt.url, in) + if tt.hidden == (got == in) || strings.Contains(got.Error(), "s3cret") || strings.Contains(got.Error(), "k3y") && tt.hidden { + t.Errorf("HideParams(%q, %q) = %q, want hidden=%v", tt.url, tt.err, got, tt.hidden) + } + } + if HideParams("postgres://app@host/db?password=s3cret&k3y=x", nil) != nil { + t.Error("HideParams should keep a nil error") + } +} + +// quotedTokens returns the text inside each matched quote pair and, as its comment says, +// starts no token at an unpaired final quote (regress finding 7). +func TestQuotedTokens(t *testing.T) { + for _, tt := range []struct { + in string + want []string + }{ + {`unrecognized configuration parameter "k3y"`, []string{"k3y"}}, + {`invalid log parameter 'ab': parsing "ab"`, []string{"ab", "ab"}}, + {`a "b`, nil}, // unpaired final '"' starts no token + {`can't connect: "x"`, []string{"x"}}, // the apostrophe in can't is an unpaired final ' + } { + got := quotedTokens(tt.in) + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("quotedTokens(%q) = %#v, want %#v", tt.in, got, tt.want) + } + } +} + // 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) { diff --git a/internal/db/mssql/mssql_test.go b/internal/db/mssql/mssql_test.go index c73158a..7658751 100644 --- a/internal/db/mssql/mssql_test.go +++ b/internal/db/mssql/mssql_test.go @@ -40,6 +40,23 @@ func TestConnectParseErrorHidesPassword(t *testing.T) { } } +// A password parameter's value may run past an '&' (password=Sec&ret); the URL Connect +// parses again hides all that follows the '=', so the error for a URL net/url can't parse +// holds none of it. +func TestConnectParseErrorHidesPasswordParameter(t *testing.T) { + for url, reason := range map[string]string{ + "sqlserver://localhost:1x?database=app&password=Sec&ret": "invalid port", + "sqlserver://local host?database=app&password=Sec&ret": "invalid character", + "sqlserver://localhost?database=app&password=Sec&ret\x7f": "percent-encode", // the URL parsed again doesn't fail + } { + err := New().Connect(context.Background(), url, "disable", time.Second) + if err == nil || strings.Contains(err.Error(), "Sec") || strings.Contains(err.Error(), "ret") || + !strings.Contains(err.Error(), "password=***") || !strings.Contains(err.Error(), reason) { + t.Errorf("%q: expected an error with %q, without the password, got %v", url, reason, err) + } + } +} + func TestEnsureMigrationsTable(t *testing.T) { db, mock, err := sqlmock.New() if err != nil { diff --git a/internal/db/postgres/postgres.go b/internal/db/postgres/postgres.go index c5aa3a2..3a79f96 100644 --- a/internal/db/postgres/postgres.go +++ b/internal/db/postgres/postgres.go @@ -5,6 +5,7 @@ import ( "fmt" "time" + "github.com/jackc/pgx/v5/pgconn" "github.com/jackc/pgx/v5/pgxpool" "github.com/meru143/dbdiff/internal/db/dsn" "github.com/meru143/dbdiff/pkg/types" @@ -15,6 +16,21 @@ const ( baseRetryDelay = 500 * time.Millisecond ) +// safeReasons are pgx's parse reasons that name no value, so connectOnce shows them for a URL +// whose password parameter may run on past an '&'. Any other reason may repeat part of what +// follows the password, escaped or trimmed (unknown target_session_attrs value: x), and gets +// the generic hint instead. +var safeReasons = []string{ + "invalid port", + "failed to configure TLS (sslmode is invalid)", + "failed to configure TLS (unable to add CA to cert pool)", + "failed to configure TLS (failed to decode sslkey)", + "failed to configure TLS (unable to find sslpassword)", + "invalid connect_timeout (negative timeout)", + "min_protocol_version cannot be greater than max_protocol_version", + "pool_max_conns too small", +} + // Driver implements db.Driver for PostgreSQL using pgx type Driver struct { pool *pgxpool.Pool @@ -78,14 +94,29 @@ func (d *Driver) Connect(ctx context.Context, connStr, sslMode string, timeout t func connectOnce(ctx context.Context, connStr, sslMode string, timeout time.Duration) (*pgxpool.Pool, error) { config, err := pgxpool.ParseConfig(connStr) if err != nil { - // pgx hides the password in the URL it quotes, but its reason can quote part of it: - // in a malformed URL the password spills into the host or the path, and pgx quotes - // an invalid escape there. The redacted URL fails only if the rest of it does, and - // its error holds no password. - if _, rerr := pgxpool.ParseConfig(dsn.Redact(connStr)); rerr != nil { - return nil, fmt.Errorf("failed to parse connection string: %w", rerr) + // pgx hides the password in the URL it quotes, but when the query holds a password + // parameter, its reason and that URL can hold part of what follows the parameter's + // '=': a raw '&' pgx read as its own parameter, or a value it repeats. Re-parse a copy + // whose password is masked but whose other parameters stay (RedactToSeparator), so pgx + // still reports a genuinely bad one. With no password parameter, show its error, + // redacted. With one, show only a reason that names no value (safeReasons), after the + // URL redacted, never pgx's own text; otherwise give the hint, which a bad parameter + // after the password, or the password value itself, falls to. + rs := dsn.RedactToSeparator(connStr) + if _, rerr := pgxpool.ParseConfig(rs); rerr != nil { + if !dsn.HasPasswordParam(connStr) { + return nil, fmt.Errorf("failed to parse connection string: %s", dsn.Redact(rerr.Error())) + } + // pgx's own prefix for rs (cannot parse `…`: ), so the whole error is compared and + // a value that ends in "`: invalid port" can't pass for that reason. + prefix := pgconn.NewParseConfigError(rs, "", nil).Error() + for _, r := range safeReasons { + if rerr.Error() == prefix+r { + return nil, fmt.Errorf("failed to parse connection string %q: %s", dsn.Redact(connStr), r) + } + } } - return nil, fmt.Errorf("failed to parse connection string %q: percent-encode the special characters in its user name and password", dsn.Redact(connStr)) + return nil, fmt.Errorf("failed to parse connection string %q: percent-encode the special characters in its user name and password, or correct a parameter after the password", dsn.Redact(connStr)) } if sslMode == "disable" { diff --git a/internal/db/postgres/postgres_test.go b/internal/db/postgres/postgres_test.go index 9d8ed71..2af1487 100644 --- a/internal/db/postgres/postgres_test.go +++ b/internal/db/postgres/postgres_test.go @@ -25,3 +25,89 @@ func TestConnectParseErrorHidesPassword(t *testing.T) { t.Errorf("an sslmode error should keep its reason, not the password, got %v", err) } } + +// pgx ends a password parameter's value at the next '&', and when what follows fails to +// parse, its reason quotes it, though it may be the rest of the password. The URL +// connectOnce parses again hides all that follows the '=', so its error holds none of it. +func TestConnectParseErrorHidesPasswordParameter(t *testing.T) { + for _, url := range []string{ + "postgres://app@localhost:5432/db?sslmode=disable&password=QZXa&QZYb", // missing key/value separator "=" in URI query parameter: "QZYb" + "postgres://app@localhost/db?password=QZXa&QZYb", + "postgres://app@localhost:5432/db?password=QZXa&QZYb=QZYc=QZYd", // extra key/value separator "=" in URI query parameter: "QZYb" + "postgres://app:QZXa@localhost:5432/db?sslmode=disable&sslpassword=QZXb&QZYb", + "postgres://app@localhost:5x/db?password=QZXa&QZYb", // invalid port: the URL parsed again fails too + // A 1-2 character piece after a raw '&' must not show either (regress/leaks finding 1). + "postgres://app@localhost:5432/db?sslmode=disable&password=QZXa&Zq", // missing key/value separator "=" ... "Zq" + "postgres://app@localhost/db?password=QZXa&9a", // "9a" + "postgres://app@localhost:5432/db?password=QZXa&ab=QZYc=QZYd", // extra key/value separator "=" ... "ab" + "postgres://app:QZXa@localhost:5432/db?sslmode=disable&sslpassword=QZXb&Qz", + } { + _, err := connectOnce(context.Background(), url, "disable", time.Second) + if err == nil || strings.Contains(err.Error(), "QZX") || strings.Contains(err.Error(), "QZY") || + strings.Contains(err.Error(), "Zq") || strings.Contains(err.Error(), "9a") || + strings.Contains(err.Error(), `"ab"`) || strings.Contains(err.Error(), "Qz") || + !strings.Contains(err.Error(), "password=") { + t.Errorf("%s: expected an error naming the URL without its password, got %v", url, err) + } + } +} + +// A parameter after the password whose value pgx echoes (unknown +// target_session_attrs value, a bad sslrootcert path) gives the generic hint, not the value, +// since the value may be the rest of the password (regress finding 2). connect_timeout and +// pool_max_conns, which also quote their value, do the same, and so does any reason not in +// safeReasons; a safe one is shown with the URL redacted, never pgx's quoted URL. +func TestConnectParseErrorHintsOnParamValue(t *testing.T) { + for _, url := range []string{ + "postgres://app@127.0.0.1:1/db?password=Zq9simple&target_session_attrs=QZtS", + "postgres://app@127.0.0.1:1/db?password=Zq9simple&channel_binding=QZcB", + "postgres://app@127.0.0.1:1/db?password=Zq9simple&sslrootcert=QZrC", + "postgres://app@127.0.0.1:1/db?password=Zq9simple&connect_timeout=QZen", + "postgres://app@127.0.0.1:1/db?password=Zq9simple&pool_max_conns=QZmy", + // values that hold the punctuation pgx wraps values in + "postgres://app@127.0.0.1:1/db?password=Zq9simple&target_session_attrs=QZ:tS", + "postgres://app@127.0.0.1:1/db?password=Zq9simple&channel_binding=QZ:cB", + "postgres://app@127.0.0.1:1/db?password=Zq9simple&sslrootcert=QZ:rC", + "postgres://app@127.0.0.1:1/db?password=Zq9simple&target_session_attrs=QZ(tS)", + "postgres://app@127.0.0.1:1/db?password=Zq9simple&sslrootcert=QZ(rC)", + // a value that also appears as a parameter name + "postgres://app@127.0.0.1:1/db?password=Zq9simple&target_session_attrs=QZ:tS&QZ:tS=other", + // values pgx escapes or trims before it repeats them + `postgres://app@127.0.0.1:1/db?password=Zq9simple&connect_timeout=QZ\tS`, + `postgres://app@127.0.0.1:1/db?password=Zq9simple&pool_max_conns="QZtS"`, + `postgres://app@127.0.0.1:1/db?password=Zq9simple&min_protocol_version=QZ"tS`, + "postgres://app@127.0.0.1:1/db?password=Zq9simple&require_auth=!QZ:tS", + "postgres://app@127.0.0.1:1/db?password=Zq9simple&pool_ping_timeout=QZ%C3%A9tS", + // a bad escape in the password, and a backtick that would end pgx's quoted URL early + "postgres://app@127.0.0.1:1/db?password=50%off&channel_binding=QZ%28cB%29", + "postgres://app@127.0.0.1:1/db?password=Zq9simple&sslmode=`QZtS`", + } { + _, err := connectOnce(context.Background(), url, "disable", time.Second) + if err == nil || strings.Contains(err.Error(), "QZ") || !strings.Contains(err.Error(), "password=***") { + t.Errorf("%s: want the generic hint without the value, got %v", url, err) + } + } +} + +// A parameter after the password that pgx rejects keeps its reason in the error, with the +// password hidden. Ending the redaction at the password hid the faulty parameter too and left +// only a generic hint; connectOnce re-parses a copy that keeps the parameters (a raw '&' tail, +// which pgx can't tell from one, still gets the hint — see the test above). +func TestConnectParseErrorKeepsParamReason(t *testing.T) { + for _, tt := range []struct{ url, reason string }{ + {"postgres://app@127.0.0.1:1/db?password=QZXa&sslmode=disabled", "sslmode is invalid"}, + {"postgres://127.0.0.1:1/db?password=QZXa&user=app&port=abc", "invalid port"}, + {"postgres://app@127.0.0.1:1/db?password=QZXa&connect_timeout=-5", "invalid connect_timeout (negative timeout)"}, + {"postgres://app@127.0.0.1:1/db?password=QZXa&pool_max_conns=0", "pool_max_conns too small"}, + } { + _, err := connectOnce(context.Background(), tt.url, "disable", time.Second) + if err == nil || strings.Contains(err.Error(), "QZX") || !strings.Contains(err.Error(), tt.reason) { + t.Errorf("%s: want the reason %q without the password, got %v", tt.url, tt.reason, err) + } + } + // A value pgx repeats that ends like a safe reason gets the hint, not that reason. + url := "postgres://app@127.0.0.1:1/db?password=QZXa&target_session_attrs=x%60:%20invalid%20port" + if _, err := connectOnce(context.Background(), url, "disable", time.Second); err == nil || !strings.Contains(err.Error(), "percent-encode") { + t.Errorf("%s: want the generic hint, got %v", url, err) + } +} diff --git a/internal/db/registry.go b/internal/db/registry.go index c91c57c..40ef67c 100644 --- a/internal/db/registry.go +++ b/internal/db/registry.go @@ -5,6 +5,7 @@ import ( "fmt" "slices" "strings" + "time" "github.com/meru143/dbdiff/internal/db/dsn" "github.com/meru143/dbdiff/internal/db/mssql" @@ -56,6 +57,12 @@ func NewDriver(connStr string) (Driver, error) { // the history. type withoutMigrationsTable struct{ Driver } +// Connect leaves out a driver's error that quotes what Redact hides after a password +// parameter (see dsn.HideParams): every driver NewDriver makes connects through it. +func (d withoutMigrationsTable) Connect(ctx context.Context, connStr, sslMode string, timeout time.Duration) error { + return dsn.HideParams(connStr, d.Driver.Connect(ctx, connStr, sslMode, timeout)) +} + func (d withoutMigrationsTable) Introspect(ctx context.Context, schema string, ignorePatterns []string) (*types.Schema, error) { s, err := d.Driver.Introspect(ctx, schema, ignorePatterns) if err != nil { diff --git a/internal/db/registry_test.go b/internal/db/registry_test.go index d17b2eb..d1f12b6 100644 --- a/internal/db/registry_test.go +++ b/internal/db/registry_test.go @@ -2,8 +2,10 @@ package db import ( "context" + "errors" "strings" "testing" + "time" "github.com/meru143/dbdiff/pkg/types" ) @@ -48,3 +50,30 @@ func TestNewDriverErrorHidesURL(t *testing.T) { } } } + +type failingConnect struct { + Driver + err error +} + +func (f failingConnect) Connect(context.Context, string, string, time.Duration) error { return f.err } + +// Every driver NewDriver makes connects through dsn.HideParams: an error that quotes what +// follows a password parameter's '=' is left out, and the others pass through. +func TestConnectHidesParamsAfterPassword(t *testing.T) { + quoting := errors.New(`server error: FATAL: unrecognized configuration parameter "k3y" (SQLSTATE 42704)`) + err := withoutMigrationsTable{failingConnect{err: quoting}}.Connect(context.Background(), "postgres://app@host/db?password=s3cret&k3y=x", "disable", time.Second) + if err == nil || strings.Contains(err.Error(), "k3y") || strings.Contains(err.Error(), "s3cret") { + t.Errorf("expected an error without the parameter, got %v", err) + } + other := errors.New("connection refused") + if err := (withoutMigrationsTable{failingConnect{err: other}}).Connect(context.Background(), "postgres://app@host/db?password=s3cret&k3y=x", "disable", time.Second); err != other { + t.Errorf("expected the driver's error, got %v", err) + } + // go-mssqldb names a duplicated key without quotes; it is hidden too when it follows the + // password parameter. + dupKey := errors.New("key k3y provided more than once") + if err := (withoutMigrationsTable{failingConnect{err: dupKey}}).Connect(context.Background(), "sqlserver://host?database=db&password=s3cret&k3y&k3y", "disable", time.Second); err == nil || strings.Contains(err.Error(), "k3y") || strings.Contains(err.Error(), "s3cret") { + t.Errorf("expected the duplicate key hidden, got %v", err) + } +} diff --git a/main.go b/main.go index 6d27110..38742ab 100644 --- a/main.go +++ b/main.go @@ -3,6 +3,7 @@ package main import ( "fmt" "os" + "strings" "time" "github.com/meru143/dbdiff/cmd" @@ -85,8 +86,11 @@ func init() { // Add PersistentPreRun for setup rootCmd.PersistentPreRun = func(cmd *cobra.Command, args []string) { - // Load config file if specified - if cfg := viper.GetString("config"); cfg != "" { + // Load config file if specified. A URL in its place is no file, and isn't read as one + // (see config.Load). + if cfg := viper.GetString("config"); strings.Contains(cfg, "://") { + fmt.Fprintf(os.Stderr, "Warning: Failed to read config file: --config takes a file, not a URL: %s\n", dsn.Redact(cfg)) + } else if cfg != "" { viper.SetConfigFile(cfg) if err := viper.ReadInConfig(); err != nil { fmt.Fprintf(os.Stderr, "Warning: Failed to read config file: %v\n", dsn.Redact(err.Error())) diff --git a/main_test.go b/main_test.go index d43a4c6..49f5d7a 100644 --- a/main_test.go +++ b/main_test.go @@ -8,6 +8,7 @@ import ( "testing" "github.com/spf13/cobra" + "github.com/spf13/viper" ) // dbdiff --help opens with what dbdiff does: all three databases, not only PostgreSQL. @@ -87,3 +88,28 @@ func TestCompletionHidesPassword(t *testing.T) { } } } + +// root's PersistentPreRun doesn't give viper a URL given for --config, or in DBDIFF_CONFIG, +// to read as a file. (config.Load, which reads --config again, printed part of the password +// viper took for the file's type: Unsupported Config Type "QZYb@localhost:5432".) +func TestConfigURLIsNotRead(t *testing.T) { + viper.Set("config", "postgres://app:QZXa.QZYb@localhost:5432") + stderr := os.Stderr + t.Cleanup(func() { + os.Stderr = stderr + viper.Set("config", "") + }) + r, w, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + os.Stderr = w + rootCmd.PersistentPreRun(rootCmd, nil) + os.Stderr = stderr + w.Close() + printed, _ := io.ReadAll(r) + r.Close() + if got := string(printed); strings.Contains(got, "QZ") || !strings.Contains(got, "not a URL: postgres://app:***@localhost:5432\n") { + t.Errorf("expected a warning naming the URL without its password, got %q", got) + } +}