Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix in the URL parser with go 1.12.8 and github.com/go-sql-driver/mysql #265

Merged
merged 6 commits into from
Aug 17, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 28 additions & 32 deletions database/mysql/mysql.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ import (
)

import (
"github.com/golang-migrate/migrate/v4"
"github.com/golang-migrate/migrate/v4/database"
)

Expand Down Expand Up @@ -98,43 +97,35 @@ func WithInstance(instance *sql.DB, config *Config) (database.Driver, error) {
return mx, nil
}

// urlToMySQLConfig takes a net/url URL and returns a go-sql-driver/mysql Config.
// Manually sets username and password to avoid net/url from url-encoding the reserved URL characters
func urlToMySQLConfig(u nurl.URL) (*mysql.Config, error) {
origUserInfo := u.User
u.User = nil

c, err := mysql.ParseDSN(strings.TrimPrefix(u.String(), "mysql://"))
func urlToMySQLConfig(url string) (*mysql.Config, error) {
config, err := mysql.ParseDSN(strings.TrimPrefix(url, "mysql://"))
if err != nil {
return nil, err
}
if origUserInfo != nil {
c.User = origUserInfo.Username()
if p, ok := origUserInfo.Password(); ok {
c.Passwd = p
}
}
return c, nil
}

func (m *Mysql) Open(url string) (database.Driver, error) {
purl, err := nurl.Parse(url)
config.MultiStatements = true

// Keep backwards compatibility from when we used net/url.Parse() to parse the DSN.
// net/url.Parse() would automatically unescape it for us.
// See: https://play.golang.org/p/q9j1io-YICQ
user, err := nurl.QueryUnescape(config.User)
if err != nil {
return nil, err
}
config.User = user

q := purl.Query()
q.Set("multiStatements", "true")
purl.RawQuery = q.Encode()

migrationsTable := purl.Query().Get("x-migrations-table")
password, err := nurl.QueryUnescape(config.Passwd)
if err != nil {
return nil, err
}
config.Passwd = password

// use custom TLS?
ctls := purl.Query().Get("tls")
ctls := config.TLSConfig
if len(ctls) > 0 {
if _, isBool := readBool(ctls); !isBool && strings.ToLower(ctls) != "skip-verify" {
rootCertPool := x509.NewCertPool()
pem, err := ioutil.ReadFile(purl.Query().Get("x-tls-ca"))
pem, err := ioutil.ReadFile(config.Params["x-tls-ca"])
if err != nil {
return nil, err
}
Expand All @@ -144,7 +135,7 @@ func (m *Mysql) Open(url string) (database.Driver, error) {
}

clientCert := make([]tls.Certificate, 0, 1)
if ccert, ckey := purl.Query().Get("x-tls-cert"), purl.Query().Get("x-tls-key"); ccert != "" || ckey != "" {
if ccert, ckey := config.Params["x-tls-cert"], config.Params["x-tls-key"]; ccert != "" || ckey != "" {
if ccert == "" || ckey == "" {
return nil, ErrTLSCertKeyConfig
}
Expand All @@ -156,8 +147,8 @@ func (m *Mysql) Open(url string) (database.Driver, error) {
}

insecureSkipVerify := false
if len(purl.Query().Get("x-tls-insecure-skip-verify")) > 0 {
x, err := strconv.ParseBool(purl.Query().Get("x-tls-insecure-skip-verify"))
if len(config.Params["x-tls-insecure-skip-verify"]) > 0 {
x, err := strconv.ParseBool(config.Params["x-tls-insecure-skip-verify"])
if err != nil {
return nil, err
}
Expand All @@ -175,18 +166,23 @@ func (m *Mysql) Open(url string) (database.Driver, error) {
}
}

c, err := urlToMySQLConfig(*migrate.FilterCustomQuery(purl))
return config, nil
}

func (m *Mysql) Open(url string) (database.Driver, error) {
config, err := urlToMySQLConfig(url)
if err != nil {
return nil, err
}
db, err := sql.Open("mysql", c.FormatDSN())

db, err := sql.Open("mysql", config.FormatDSN())
if err != nil {
return nil, err
}

mx, err := WithInstance(db, &Config{
DatabaseName: purl.Path,
MigrationsTable: migrationsTable,
DatabaseName: config.DBName,
MigrationsTable: config.Params["x-migrations-table"],
})
if err != nil {
return nil, err
Expand Down
15 changes: 4 additions & 11 deletions database/mysql/mysql_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import (
"log"

"github.com/golang-migrate/migrate/v4"
"net/url"
"testing"
)

Expand Down Expand Up @@ -210,19 +209,13 @@ func TestURLToMySQLConfig(t *testing.T) {
}
for _, tc := range testcases {
t.Run(tc.name, func(t *testing.T) {
u, err := url.Parse(tc.urlStr)
config, err := urlToMySQLConfig(tc.urlStr)
if err != nil {
t.Fatal("Failed to parse url string:", tc.urlStr, "error:", err)
}
if config, err := urlToMySQLConfig(*u); err == nil {
dsn := config.FormatDSN()
if dsn != tc.expectedDSN {
t.Error("Got unexpected DSN:", dsn, "!=", tc.expectedDSN)
}
} else {
if tc.expectedDSN != "" {
t.Error("Got unexpected error:", err, "urlStr:", tc.urlStr)
}
dsn := config.FormatDSN()
if dsn != tc.expectedDSN {
t.Error("Got unexpected DSN:", dsn, "!=", tc.expectedDSN)
}
})
}
Expand Down
9 changes: 3 additions & 6 deletions database/parse_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -139,8 +139,7 @@ func TestPasswordUnencodedReservedURLChars(t *testing.T) {
}{
{char: "!", parses: true, expectedUsername: username, expectedPassword: basePassword + "!",
encodedURL: schemeAndUsernameAndSep + basePassword + "%21" + urlSuffixAndSep},
{char: "#", parses: true, expectedUsername: "", expectedPassword: "",
encodedURL: schemeAndUsernameAndSep + basePassword + "#" + urlSuffixAndSep},
{char: "#", parses: false},
Copy link
Member

Choose a reason for hiding this comment

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

Why did these tests break? My understanding is that the hostname/port parsing was fixed. I don't see any changes to parseAuthority() in the fix: golang/go@3226f2d

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I don't see where it changed either but it did: https://play.golang.org/p/gQLxfWBQnQD

Copy link
Member

Choose a reason for hiding this comment

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

Looks like these characters needed to be percent-encoded in the first place.

ABNF for authority part of an URI:

authority     = [ userinfo "@" ] host [ ":" port ]
userinfo      = *( unreserved / pct-encoded / sub-delims / ":" )
unreserved    = ALPHA / DIGIT / "-" / "." / "_" / "~"
pct-encoded   = "%" HEXDIG HEXDIG
sub-delims    = "!" / "$" / "&" / "'" / "(" / ")"
                 / "*" / "+" / "," / ";" / "="

https://tools.ietf.org/html/rfc3986#appendix-A

{char: "$", parses: true, expectedUsername: username, expectedPassword: basePassword + "$",
encodedURL: schemeAndUsernameAndSep + basePassword + "$" + urlSuffixAndSep},
{char: "%", parses: false},
Expand All @@ -158,16 +157,14 @@ func TestPasswordUnencodedReservedURLChars(t *testing.T) {
encodedURL: schemeAndUsernameAndSep + basePassword + "+" + urlSuffixAndSep},
{char: ",", parses: true, expectedUsername: username, expectedPassword: "password,",
encodedURL: schemeAndUsernameAndSep + basePassword + "," + urlSuffixAndSep},
{char: "/", parses: true, expectedUsername: "", expectedPassword: "",
encodedURL: schemeAndUsernameAndSep + basePassword + "/" + urlSuffixAndSep},
{char: "/", parses: false},
{char: ":", parses: true, expectedUsername: username, expectedPassword: "password:",
encodedURL: schemeAndUsernameAndSep + basePassword + "%3A" + urlSuffixAndSep},
{char: ";", parses: true, expectedUsername: username, expectedPassword: "password;",
encodedURL: schemeAndUsernameAndSep + basePassword + ";" + urlSuffixAndSep},
{char: "=", parses: true, expectedUsername: username, expectedPassword: "password=",
encodedURL: schemeAndUsernameAndSep + basePassword + "=" + urlSuffixAndSep},
{char: "?", parses: true, expectedUsername: "", expectedPassword: "",
encodedURL: schemeAndUsernameAndSep + basePassword + "?" + urlSuffixAndSep},
{char: "?", parses: false},
{char: "@", parses: true, expectedUsername: username, expectedPassword: "password@",
encodedURL: schemeAndUsernameAndSep + basePassword + "%40" + urlSuffixAndSep},
{char: "[", parses: false},
Expand Down
11 changes: 5 additions & 6 deletions util.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,15 +74,14 @@ func schemeFromURL(url string) (string, error) {
return "", errEmptyURL
}

u, err := nurl.Parse(url)
if err != nil {
return "", err
}
if len(u.Scheme) == 0 {
i := strings.Index(url, ":")

// No : or : is the first character.
Copy link
Member

Choose a reason for hiding this comment

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

Thanks for the comment!

if i < 1 {
return "", errNoScheme
}

return u.Scheme, nil
return url[0:i], nil
}

// FilterCustomQuery filters all query values starting with `x-`
Expand Down
35 changes: 27 additions & 8 deletions util_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,15 +74,34 @@ func TestSourceSchemeFromUrlFailure(t *testing.T) {
}

func TestDatabaseSchemeFromUrlSuccess(t *testing.T) {
urlStr := "protocol://path"
expected := "protocol"

u, err := databaseSchemeFromURL(urlStr)
if err != nil {
t.Fatalf("expected no error, but received %q", err)
cases := []struct {
name string
urlStr string
expected string
}{
{
name: "Simple",
urlStr: "protocol://path",
expected: "protocol",
},
{
// See issue #264
name: "MySQLWithPort",
urlStr: "mysql://user:pass@tcp(host:1337)/db",
expected: "mysql",
},
}
if u != expected {
t.Fatalf("expected %q, but received %q", expected, u)

for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
u, err := databaseSchemeFromURL(tc.urlStr)
if err != nil {
t.Fatalf("expected no error, but received %q", err)
}
if u != tc.expected {
t.Fatalf("expected %q, but received %q", tc.expected, u)
}
})
}
}

Expand Down