Merge pull request #10922 from hashicorp/idubinskiy-postgres-dsn-quote

provider/postgresql: Quote connection string parameters
This commit is contained in:
Sean Chittenden 2016-12-25 05:59:34 -08:00 committed by GitHub
commit e508a3b59d
3 changed files with 26 additions and 5 deletions

View File

@ -4,7 +4,8 @@ PSQL?=/opt/local/lib/postgresql96/bin/psql
PGDATA?=$(GOPATH)/src/github.com/hashicorp/terraform/builtin/providers/postgresql/data
initdb::
/opt/local/lib/postgresql96/bin/initdb --no-locale -U postgres -D $(PGDATA)
echo "" > pwfile
/opt/local/lib/postgresql96/bin/initdb --no-locale -U postgres -A md5 --pwfile=pwfile -D $(PGDATA)
startdb::
2>&1 \
@ -18,6 +19,7 @@ startdb::
cleandb::
rm -rf $(PGDATA)
rm -f pwfile
freshdb:: cleandb initdb startdb

View File

@ -1,6 +1,7 @@
package postgresql
import (
"bytes"
"database/sql"
"fmt"
"log"
@ -33,10 +34,29 @@ func (c *Config) NewClient() (*Client, error) {
// user.
const dsnFmt = "host=%s port=%d dbname=%s user=%s password=%s sslmode=%s fallback_application_name=%s connect_timeout=%d"
logDSN := fmt.Sprintf(dsnFmt, c.Host, c.Port, c.Database, c.Username, "<redacted>", c.SSLMode, c.ApplicationName, c.ConnectTimeoutSec)
// Quote empty strings or strings that contain whitespace
q := func(s string) string {
b := bytes.NewBufferString(`'`)
b.Grow(len(s) + 2)
for _, r := range s {
switch r {
case '\'':
b.WriteString(`\'`)
case '\\':
b.WriteString(`\\`)
default:
b.WriteRune(r)
}
}
b.WriteString(`'`)
return b.String()
}
logDSN := fmt.Sprintf(dsnFmt, q(c.Host), c.Port, q(c.Database), q(c.Username), q("<redacted>"), q(c.SSLMode), q(c.ApplicationName), c.ConnectTimeoutSec)
log.Printf("[INFO] PostgreSQL DSN: `%s`", logDSN)
connStr := fmt.Sprintf(dsnFmt, c.Host, c.Port, c.Database, c.Username, c.Password, c.SSLMode, c.ApplicationName, c.ConnectTimeoutSec)
connStr := fmt.Sprintf(dsnFmt, q(c.Host), c.Port, q(c.Database), q(c.Username), q(c.Password), q(c.SSLMode), q(c.ApplicationName), c.ConnectTimeoutSec)
client := Client{
connStr: connStr,
username: c.Username,

View File

@ -112,11 +112,10 @@ func tfAppName() string {
const VersionPrerelease = terraform.VersionPrerelease
var versionString bytes.Buffer
fmt.Fprintf(&versionString, "'Terraform v%s", terraform.Version)
fmt.Fprintf(&versionString, "Terraform v%s", terraform.Version)
if terraform.VersionPrerelease != "" {
fmt.Fprintf(&versionString, "-%s", terraform.VersionPrerelease)
}
fmt.Fprintf(&versionString, "'")
return versionString.String()
}