Skip to content

Commit

Permalink
Use and respect the passfile connection parameter
Browse files Browse the repository at this point in the history
The postgres documentation[1] regarding the password file, states
that:

password file to use can be specified using the connection parameter
passfile or the environment variable PGPASSFILE.

The current implementation of lib/pq only respects the environment
variable PGPASSFILE. This is not correct, but also limiting, as
the PGPASSFILE is global and we might want to use different files
for different clients in the same program.

Fixing that is easy, by just checking the parameter passfile first,
and if not, pull the value from PGPASSFILE.

[1] https://www.postgresql.org/docs/current/libpq-pgpass.html
  • Loading branch information
keymon committed Jun 9, 2023
1 parent 381d253 commit 29f3a40
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 2 deletions.
6 changes: 5 additions & 1 deletion conn.go
Expand Up @@ -233,7 +233,11 @@ func (cn *conn) handlePgpass(o values) {
if _, ok := o["password"]; ok {
return
}
filename := os.Getenv("PGPASSFILE")
// Get passfile from the options, if empty, get it from envvar
filename := o["passfile"]
if filename == "" {
filename = os.Getenv("PGPASSFILE")
}
if filename == "" {
// XXX this code doesn't work on Windows where the default filename is
// XXX %APPDATA%\postgresql\pgpass.conf
Expand Down
6 changes: 5 additions & 1 deletion conn_test.go
Expand Up @@ -189,6 +189,7 @@ localhost:*:*:*:pass_C
if err != nil {
t.Fatalf("Unexpected error writing pgpass file %#v", err)
}
defer os.Remove(pgpassFile)
pgpass.Close()

assertPassword := func(extra values, expected string) {
Expand Down Expand Up @@ -221,8 +222,11 @@ localhost:*:*:*:pass_C
// localhost also matches the default "" and UNIX sockets
assertPassword(values{"host": "", "user": "some_user"}, "pass_C")
assertPassword(values{"host": "/tmp", "user": "some_user"}, "pass_C")
// passfile connection parameter takes precedence
os.Setenv("PGPASSFILE", "/tmp")
assertPassword(values{"host": "server", "dbname": "some_db", "user": "some_user", "passfile": pgpassFile}, "pass_A")

// cleanup
os.Remove(pgpassFile)
os.Setenv("PGPASSFILE", "")
}

Expand Down

0 comments on commit 29f3a40

Please sign in to comment.