From 9905791932573b134e204cfd408e38a1a601e4e5 Mon Sep 17 00:00:00 2001 From: Tatsuhito KATO Date: Mon, 13 Aug 2018 11:43:19 +0000 Subject: [PATCH] Fixes MySQL custom TLS connection failure. --- database/mysql/README.md | 1 + database/mysql/mysql.go | 30 +++++++++++++++++------------- 2 files changed, 18 insertions(+), 13 deletions(-) diff --git a/database/mysql/README.md b/database/mysql/README.md index 0cb1299..636cb53 100644 --- a/database/mysql/README.md +++ b/database/mysql/README.md @@ -10,6 +10,7 @@ | `password` | | The user's password | | `host` | | The host to connect to. | | `port` | | The port to bind to. | +| `tls` | | The custom TLS config name, use with `x-tls-` queries. | | `x-tls-ca` | | The location of the root certificate file. | | `x-tls-cert` | | Cert file location. | | `x-tls-key` | | Key file location. | diff --git a/database/mysql/mysql.go b/database/mysql/mysql.go index 85afbfa..504df33 100644 --- a/database/mysql/mysql.go +++ b/database/mysql/mysql.go @@ -123,15 +123,6 @@ func (m *Mysql) Open(url string) (database.Driver, error) { q.Set("multiStatements", "true") purl.RawQuery = q.Encode() - c, err := urlToMySQLConfig(*migrate.FilterCustomQuery(purl)) - if err != nil { - return nil, err - } - db, err := sql.Open("mysql", c.FormatDSN()) - if err != nil { - return nil, err - } - migrationsTable := purl.Query().Get("x-migrations-table") if len(migrationsTable) == 0 { migrationsTable = DefaultMigrationsTable @@ -151,9 +142,13 @@ func (m *Mysql) Open(url string) (database.Driver, error) { return nil, ErrAppendPEM } - certs, err := tls.LoadX509KeyPair(purl.Query().Get("x-tls-cert"), purl.Query().Get("x-tls-key")) - if err != nil { - return nil, err + clientCert := make([]tls.Certificate, 0, 1) + if purl.Query().Get("x-tls-cert") != "" && purl.Query().Get("x-tls-key") != "" { + certs, err := tls.LoadX509KeyPair(purl.Query().Get("x-tls-cert"), purl.Query().Get("x-tls-key")) + if err != nil { + return nil, err + } + clientCert = append(clientCert, certs) } insecureSkipVerify := false @@ -167,12 +162,21 @@ func (m *Mysql) Open(url string) (database.Driver, error) { mysql.RegisterTLSConfig(ctls, &tls.Config{ RootCAs: rootCertPool, - Certificates: []tls.Certificate{certs}, + Certificates: clientCert, InsecureSkipVerify: insecureSkipVerify, }) } } + c, err := urlToMySQLConfig(*migrate.FilterCustomQuery(purl)) + if err != nil { + return nil, err + } + db, err := sql.Open("mysql", c.FormatDSN()) + if err != nil { + return nil, err + } + mx, err := WithInstance(db, &Config{ DatabaseName: purl.Path, MigrationsTable: migrationsTable,