PostgreSQL Connection String Password Special Characters
Fix a PostgreSQL connection string whose password has special characters: percent-encode it once, check how libpq reads it, keep it off the command line.
On this page
- Which characters break a PostgreSQL connection string
- Encode the password once, with nothing marked safe
- Build DATABASE_URL without the password on a command line
- Check a DATABASE_URL you already have
- Where to put the encoded URL
- Try it: the lab
- How ox writes DATABASE_URL
- Key takeaways
- Frequently asked questions
- Next step
If your PostgreSQL password has special characters, percent-encode the password once before you put it in a postgresql:// connection string. Encode everything except letters, digits and -._~: @ becomes %40, / becomes %2F, % becomes %25 and a space becomes %20. libpq decodes it back to the real password. A raw @ or / does not fail loudly. libpq quietly reads part of your password as the host name or the port, and the connection fails later with an error that points somewhere else. Below are the characters that break, the three encoding mistakes that look right, a small script that builds a DATABASE_URL and checks it with libpq without the password ever reaching a command line, and a lab that proves all of it on a throwaway server.
How this was tested: on 3 December 2026 (UTC) I ran the lab at the end of this post and the script below as an ordinary user, in temporary folders. libpq was 18.6 in two builds: the libpq5 package from Ubuntu 26.04 (18.6-0ubuntu0.26.04.1, its SHA-256 checked against the archive's index) and the PostgreSQL project's own 18.6 build. Python was 3.12.3 and 3.14.8. All four combinations printed the same output, byte for byte. The login test used a PostgreSQL 18.6 server that the lab starts on a Unix socket in its own folder, with no TCP port. Every password was random and made at run time. The machine was Ubuntu 24.04, not a real Ubuntu 26.04 server. I build ox, which deploys apps to your own server. You need no ox for any of this.
Which characters break a PostgreSQL connection string
PostgreSQL's connection URI docs give the shape as postgresql://[userspec@][hostspec][/dbname][?paramspec], with user[:password] as the userspec, and say: "The connection URI needs to be encoded with percent-encoding if it includes symbols with special meaning in any of its parts." They do not list which symbols those are for a password, so the lab tried them one at a time. Each password was a random part A, one special character and a random part B, written raw as the password in postgresql://app:password@127.0.0.1:5432/app. This is what libpq 18.6 read:
'@' user=app password=A host=B@127.0.0.1 port=5432 dbname=app
'/' host=app port=A dbname=B@127.0.0.1:5432/app
'%' error: invalid percent-encoded token: "A%B"
' ' error: unexpected spaces found in "A B", use percent-encoded spaces (%20) instead
':' correct
'?' correct
'#' correct
'&' correct
'=' correct
'+' correct
'%41' decoded to the letter A
The first two rows are the dangerous ones, because nothing fails at parse time:
- A raw
@ends the user part at the first@. libpq takes A as the password andB@127.0.0.1as the host name, so the app tries to reach a host named after the end of your password. - A raw
/ends the host part before libpq ever sees the@. The user name became the host, A became the port, and the rest became the database name. There is no user and no password at all. - A malformed percent escape or raw space fails at once, and the error message quotes the text around it, password included. If your app logs connection errors, that part of the password is now in the log. With a valid escape such as
%41, parsing succeeds but libpq reads the letter A. Encode a literal percent sign as%25.
libpq 18.6 read :, ?, #, &, = and + correctly here, but do not rely on that. RFC 3986 allows only letters, digits, -._~, percent-encoded bytes, : and !$&'()*+,;= in the user part of a URL. ? and # are not on that list, and other code that reads the same DATABASE_URL may follow the RFC. Python's urllib.parse.urlsplit, for example, cut postgresql://app:ab#cd@127.0.0.1:5432/app at the # and returned app as the host name. Encoding every character outside letters, digits and -._~ works for every parser that follows the RFC, and libpq decodes all of it.
Encode the password once, with nothing marked safe
Three ways to encode the password look right and are not. The lab took one password, A followed by @:/?#%+&= and B, and wrote it five ways with Python's urllib.parse:
raw error: missing key/value separator "=" in URI query parameter: "#%+"
quote(pw) host=app port=A @: dbname=?#%+&=B@127.0.0.1:5432/app
quote_plus(pw) wrong password: the space came back as +
encoded twice wrong password: it came back still encoded
quote(pw, safe='') correct
quote(pw)leaves/alone. Its docs say the safe parameter's "default value is '/'", because the function is meant for URL paths. The/then cuts the URL exactly as in the raw case.quote_plus(pw)turns a space into+, which is right for HTML forms. libpq does not read+as a space, so the password it sends has a+where you had a space. Encoders made for query strings, such as Go'surl.QueryEscape, do the same.- Encoding twice happens when a value that is already encoded goes through an encoder again, often when a tool or a settings screen encodes for you.
%40becomes%2540, libpq decodes it once, and the server receives%40in place of@.
The last two parse without an error and fail only at login. The throwaway server in the lab answered both with password authentication failed and let the correctly encoded one in. That error is what you see in production too, so when a password with special characters fails, check the encoding before you reset the password. The fix is to encode the user name and the password once each, never the whole URL: quote(pw, safe='') in Python, encodeURIComponent in JavaScript, or url.UserPassword(user, pw).String() in Go. encodeURIComponent leaves !*'() as they are, which the RFC allows in the user part. In a test of 50 random passwords that held every printable ASCII symbol, a space and two non-ASCII letters, libpq read back the exact password from the output of each of the three (Node 24.21.0, Go 1.27.2).
If your app takes libpq's other format, keyword and value pairs like host=127.0.0.1 password='...', nothing needs percent-encoding. The docs say to put the value in single quotes and escape a single quote or backslash inside it with a backslash. Most frameworks read a URL, so the rest of this post builds one.
Build DATABASE_URL without the password on a command line
A one-liner like python3 -c "print(quote('my-password'))" puts the password on a command line. While it runs, any user on the server can read it with ps, unless /proc is mounted with hidepid, and your shell keeps it in its history afterwards. This script asks for the password at a hidden prompt, encodes the user name, password and database name once, checks that libpq reads back exactly what you typed, and writes the result to a new file only your user can read. It needs Python 3 and libpq, which Ubuntu installs with postgresql-client as the libpq5 package. Save it as pg-url.py:
#!/usr/bin/env python3
# pg-url.py make FILE USER HOST PORT DBNAME
# asks for the password, writes DATABASE_URL=... to a new private FILE,
# and checks that libpq reads back exactly what you typed.
# pg-url.py check FILE
# asks for the expected password and reports only whether it matches.
import ctypes, getpass, hmac, os, sys
from urllib.parse import quote
pq = ctypes.CDLL("libpq.so.5")
class Option(ctypes.Structure):
_fields_ = [("keyword", ctypes.c_char_p), ("envvar", ctypes.c_char_p),
("compiled", ctypes.c_char_p), ("val", ctypes.c_char_p),
("label", ctypes.c_char_p), ("dispchar", ctypes.c_char_p),
("dispsize", ctypes.c_int)]
pq.PQconninfoParse.restype = ctypes.POINTER(Option)
pq.PQconninfoParse.argtypes = [ctypes.c_char_p, ctypes.POINTER(ctypes.c_void_p)]
def parse(url):
err = ctypes.c_void_p()
opts = pq.PQconninfoParse(url.encode(), ctypes.byref(err))
if not opts: # libpq's message can quote the password, so it is not shown
sys.exit("libpq cannot parse this URL")
out, i = {}, 0
while opts[i].keyword:
if opts[i].val is not None:
out[opts[i].keyword.decode()] = opts[i].val
i += 1
return out
def read_url(path):
for line in open(path):
key, _, value = line.strip().partition("=")
if key in ("DATABASE_URL", "export DATABASE_URL"):
if len(value) > 1 and value[0] == value[-1] and value[0] in "'\"":
value = value[1:-1]
return value
sys.exit(f"no DATABASE_URL line in {path}")
def make(path, user, host, port, dbname):
if os.path.lexists(path):
sys.exit(f"{path} already exists; nothing written")
pw = getpass.getpass("Database password: ")
if pw != getpass.getpass("Same password again: "):
sys.exit("the two passwords differ")
url = f"postgresql://{quote(user, safe='')}:{quote(pw, safe='')}@{host}:{port}/{quote(dbname, safe='')}"
got = parse(url)
if [got.get(k) for k in ("user", "password", "host", "port", "dbname")] != [v.encode() for v in (user, pw, host, port, dbname)]:
sys.exit("libpq reads this URL differently; nothing written")
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
with open(fd, "w") as f:
f.write(f"DATABASE_URL={url}\n")
print(f"wrote DATABASE_URL to {path}; libpq reads back the same user, password, host, port and database")
def check(path):
got = parse(read_url(path))
typed = getpass.getpass("Password to compare: ")
if "password" not in got or not hmac.compare_digest(got["password"], typed.encode()):
sys.exit("password matches: NO")
print("password matches: yes")
if __name__ == "__main__":
if sys.argv[1:2] == ["make"] and len(sys.argv) == 7:
make(*sys.argv[2:])
elif sys.argv[1:2] == ["check"] and len(sys.argv) == 3:
check(sys.argv[2])
else:
sys.exit("usage: pg-url.py make FILE USER HOST PORT DBNAME | pg-url.py check FILE")
Run it as the user who will own the file, and name a file that does not exist yet:
python3 -I pg-url.py make /srv/app/shared/db.env app 127.0.0.1 5432 app
Database password:
Same password again:
wrote DATABASE_URL to /srv/app/shared/db.env; libpq reads back the same user, password, host, port and database
The file holds one line, DATABASE_URL=postgresql://app:...@127.0.0.1:5432/app, with mode 0600. If the file already exists, the script stops before it asks for anything. If libpq would read the URL differently from what you typed, it writes nothing. The host must be a host name or an IPv4 address. Given an IPv6 address, it writes nothing. The -I flag keeps Python from loading modules from the current folder.
Check a DATABASE_URL you already have
When the app says password authentication failed and you suspect the URL, the same script reads the DATABASE_URL line from a file, asks for the password you expect, and compares the two inside the process:
python3 -I pg-url.py check /srv/app/shared/db.env
For a file whose password had a raw @ in it, the output was:
Password to compare:
password matches: NO
The checker reports only whether the password matches. It omits parsed fields and parser errors because either can contain credentials. It exits with status 1 when the password does not match, so you can use it in a deploy script. It checks only what libpq reads from the URL. It does not connect, so a URL that passes can still meet a wrong password on the server.
Where to put the encoded URL
An encoded URL is full of % signs, and a systemd unit file reads % as the start of a specifier. On systemd 255, systemd-analyze verify on a unit with Environment=DATABASE_URL=postgresql://app:p%40ss@127.0.0.1:5432/app printed "Failed to resolve specifiers in DATABASE_URL=..., ignoring: Invalid slot". systemd skips that line, so the service starts without DATABASE_URL. Load the file the script wrote with EnvironmentFile=/srv/app/shared/db.env instead, which the systemd environment variables post shows leaving % alone, or write each % as %% in an Environment= line. The same post covers quotes and the restart a change needs.
Try it: the lab
This script needs Python 3 and libpq. The login test also needs the PostgreSQL server programs, which it looks for in /usr/lib/postgresql/*/bin or in the folder you name in PGBIN. Without them it skips that step. Run it as an ordinary user, since PostgreSQL refuses to start as root. It makes every password at random and never prints one: the output names the random parts A and B. For the login test it starts a server on a Unix socket in a new temporary folder, with listen_addresses empty so no TCP port opens, hands the password to initdb in a private file it deletes at once, and stops the server and removes the folder at the end. It does that too when a step fails, and when you press Ctrl-C or send kill -TERM, in which case it lets the step it is on finish first so the server is never cut off halfway.
#!/usr/bin/env python3
# How libpq reads a password in a postgresql:// URL, raw and encoded.
# Run as an ordinary user: python3 -I pg-url-lab.py
# Every password is random, made in this process, and never printed.
# The login test runs a throwaway PostgreSQL on a Unix socket in a new
# temporary folder (no TCP port), and deletes it all at the end.
import ctypes, glob, os, secrets, shutil, signal, string, subprocess, sys, tempfile
from urllib.parse import quote, quote_plus
pq = ctypes.CDLL("libpq.so.5")
class Option(ctypes.Structure):
_fields_ = [("keyword", ctypes.c_char_p), ("envvar", ctypes.c_char_p),
("compiled", ctypes.c_char_p), ("val", ctypes.c_char_p),
("label", ctypes.c_char_p), ("dispchar", ctypes.c_char_p),
("dispsize", ctypes.c_int)]
pq.PQconninfoParse.restype = ctypes.POINTER(Option)
pq.PQconninfoParse.argtypes = [ctypes.c_char_p, ctypes.POINTER(ctypes.c_void_p)]
pq.PQconninfoFree.argtypes = [ctypes.POINTER(Option)]
pq.PQfreemem.argtypes = [ctypes.c_void_p]
pq.PQconnectdb.restype = ctypes.c_void_p
pq.PQconnectdb.argtypes = [ctypes.c_char_p]
for f in ("PQstatus", "PQfinish", "PQerrorMessage", "PQexec"):
getattr(pq, f).argtypes = [ctypes.c_void_p] + ([ctypes.c_char_p] if f == "PQexec" else [])
pq.PQerrorMessage.restype = ctypes.c_char_p
pq.PQexec.restype = ctypes.c_void_p
pq.PQgetvalue.restype = ctypes.c_char_p
pq.PQgetvalue.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_int]
pq.PQclear.argtypes = [ctypes.c_void_p]
v = pq.PQlibVersion()
print(f"libpq {v // 10000}.{v % 10000}")
def parse(url):
"""libpq's own reading of a connection string, without connecting."""
err = ctypes.c_void_p()
opts = pq.PQconninfoParse(url.encode(), ctypes.byref(err))
if not opts:
msg = ctypes.cast(err, ctypes.c_char_p).value.decode()
pq.PQfreemem(err)
return None, msg.strip()
out, i = {}, 0
while opts[i].keyword:
if opts[i].val is not None:
out[opts[i].keyword.decode()] = opts[i].val.decode()
i += 1
pq.PQconninfoFree(opts)
return out, None
def rand(n):
return "".join(secrets.choice(string.ascii_letters + string.digits) for _ in range(n))
def show(text, parts):
"""text with each random part of the password replaced by its name."""
for name, part in parts:
text = text.replace(part, name)
return text
def verdict(url, pw, parts):
got, err = parse(url)
if err:
return "error: " + show(err, parts)
if got.get("password") == pw and all(got.get(k) == v for k, v in WANT.items()):
return "correct"
if got.get("password") == pw.replace(" ", "+"):
return "wrong password: the space came back as +"
if got.get("password") == quote(pw, safe=""):
return "wrong password: it came back still encoded"
return " ".join(f"{k}={show(got[k], parts)}" for k in ("user", "password", "host", "port", "dbname") if k in got)
WANT = {"user": "app", "host": "127.0.0.1", "port": "5432", "dbname": "app"}
TAIL = "@127.0.0.1:5432/app"
def main():
print("1. A password A<char>B with one special character, raw in the URL")
for c in ["@", "/", "%", " ", ":", "?", "#", "&", "=", "+"]:
a, b = rand(8), "x" + rand(7) # b starts with x, which is not hex
print(f" {c!r:5} {verdict('postgresql://app:' + a + c + b + TAIL, a + c + b, [('A', a), ('B', b)])}")
got, err = parse("postgresql://app:" + a + "%41" + b + TAIL)
assert err is None and got["password"] == a + "A" + b
print(" '%41' decoded to the letter A")
a, b = rand(12), rand(4)
pw = a + " @:/?#%+&=" + b
parts = [("A", a), ("B", b)]
print("2. The password A @:/?#%+&=B, written five ways")
ways = [("raw", pw),
("quote(pw)", quote(pw)),
("quote_plus(pw)", quote_plus(pw)),
("encoded twice", quote(quote(pw, safe=""), safe="")),
("quote(pw, safe='')", quote(pw, safe=""))]
for name, enc in ways:
print(f" {name:20} {verdict('postgresql://app:' + enc + TAIL, pw, parts)}")
bindir = os.environ.get("PGBIN") or next(iter(sorted(glob.glob("/usr/lib/postgresql/*/bin"), reverse=True)), "")
for key in list(os.environ):
if key.startswith("PG"):
del os.environ[key]
os.environ["LC_ALL"] = "C"
if not os.path.exists(os.path.join(bindir, "initdb")):
print("3. Skipped: no PostgreSQL server programs (set PGBIN to their folder)")
return
if os.geteuid() == 0:
sys.exit("run this as an ordinary user: PostgreSQL refuses to start as root")
temp_root = tempfile.gettempdir()
if not all(c in string.ascii_letters + string.digits + "/._-" for c in temp_root):
sys.exit("set TMPDIR to a simple absolute directory path")
lab = tempfile.mkdtemp(prefix="pg-url-lab-")
started = False
try:
stop_if_asked()
pwfile = os.path.join(lab, "pw")
with open(os.open(pwfile, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), "w") as f:
f.write(pw + "\n")
subprocess.run([bindir + "/initdb", "-D", lab + "/data", "-U", "lab", "--pwfile", pwfile,
"-A", "scram-sha-256", "--no-locale", "-E", "UTF8", "--no-instructions"],
check=True, stdout=subprocess.DEVNULL, start_new_session=True)
os.remove(pwfile)
stop_if_asked()
started = True
subprocess.run([bindir + "/pg_ctl", "-D", lab + "/data", "-l", lab + "/log", "-w", "start",
"-o", f"-c listen_addresses='' -k {lab}"], check=True, stdout=subprocess.DEVNULL,
start_new_session=True)
print("3. Log in to a throwaway server with the three URLs that parse")
for name, enc in ways[2:]:
stop_if_asked()
conn = pq.PQconnectdb(f"postgresql://lab:{enc}@/postgres?host={lab}".encode())
if pq.PQstatus(conn) == 0:
res = pq.PQexec(conn, b"SELECT current_user")
result = "logged in as " + pq.PQgetvalue(res, 0, 0).decode()
pq.PQclear(res)
else:
msg = pq.PQerrorMessage(conn).decode()
result = "refused: " + ("password authentication failed" if "password authentication failed" in msg else "other error")
pq.PQfinish(conn)
print(f" {name:20} {result}")
expected = "logged in as lab" if name == "quote(pw, safe='')" else "refused: password authentication failed"
if result != expected:
sys.exit("unexpected login result")
finally:
if started:
subprocess.run([bindir + "/pg_ctl", "-D", lab + "/data", "-m", "immediate", "-w", "stop"],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)
shutil.rmtree(lab)
print("removed the lab folder: " + ("yes" if not os.path.exists(lab) else "NO"))
# Ctrl-C or kill -TERM lets the current step finish, then the lab stops
# the server and removes its folder. The server programs run in their own
# session, so Ctrl-C never cuts them off halfway through.
asked = []
def stop_if_asked():
if asked:
sys.exit(130)
signal.signal(signal.SIGINT, lambda *_: asked.append(1))
signal.signal(signal.SIGTERM, lambda *_: asked.append(1))
main()
python3 -I pg-url-lab.py
This is the output from all four builds:
libpq 18.6
1. A password A<char>B with one special character, raw in the URL
'@' user=app password=A host=B@127.0.0.1 port=5432 dbname=app
'/' host=app port=A dbname=B@127.0.0.1:5432/app
'%' error: invalid percent-encoded token: "A%B"
' ' error: unexpected spaces found in "A B", use percent-encoded spaces (%20) instead
':' correct
'?' correct
'#' correct
'&' correct
'=' correct
'+' correct
'%41' decoded to the letter A
2. The password A @:/?#%+&=B, written five ways
raw error: missing key/value separator "=" in URI query parameter: "#%+"
quote(pw) host=app port=A @: dbname=?#%+&=B@127.0.0.1:5432/app
quote_plus(pw) wrong password: the space came back as +
encoded twice wrong password: it came back still encoded
quote(pw, safe='') correct
3. Log in to a throwaway server with the three URLs that parse
quote_plus(pw) refused: password authentication failed
encoded twice refused: password authentication failed
quote(pw, safe='') logged in as lab
removed the lab folder: yes
To be sure the checks can fail, I also ran changed copies. When the lab encoded with quote(pw) in place of quote(pw, safe=''), the last row of step 2 stopped reading correct, and step 3 had no login. When pg-url.py encoded the same way, it refused to write the file. While the lab ran, a watcher read the command line of every process on the machine, and none held a password. The server's log, copied out before cleanup, held the failed logins without a password. I also sent Ctrl-C or kill -TERM at 28 moments over the run (14 landed before it finished and stopped it), and made pg_ctl start fail once. After every run no folder and no server process was left behind.
How ox writes DATABASE_URL
When your ox.toml has [services] postgres = {}, ox makes the password for the project's database itself: 32 random characters, only letters and digits. The postgresql:// URL it builds from it and hands your app as DATABASE_URL therefore has nothing to encode, so none of the failures above can happen to it. The password is made once and kept for later deploys. The services section of the config reference lists what each service provides, and the variables guide shows how to build another variable from its parts, such as ${postgres.password}.
Key takeaways
- A raw
@or/in the password does not fail at parse time: libpq reads part of the password as the host, port or database. - Percent-encode the user name and password once, with nothing marked safe:
quote(pw, safe='')in Python,encodeURIComponentin JavaScript,url.UserPasswordin Go. quote()with its default leaves/,quote_plus()turns a space into+, and double encoding sends%40. All three end inpassword authentication failedor a wrong host.- libpq's parse errors quote the password, and a command line shows it to
ps, so build and check the URL in a script that asks at a prompt. - In a systemd unit, load the URL with
EnvironmentFile=or write%%, since%40inEnvironment=drops the whole variable.
Frequently asked questions
Which characters must be encoded in a PostgreSQL connection string password?
Encode everything except letters, digits and the four characters -._~. libpq 18.6 misreads a raw @ or /, and rejects a malformed percent escape or raw space. A valid escape like %41 silently becomes A. It tolerated ? and #, but other URL parsers do not, so encode those too. In Python, use quote(password, safe='').
Why does my encoded password still fail with password authentication failed?
Usually the password was encoded twice, or a space was turned into a plus sign by quote_plus or a query string encoder. libpq decodes once, so the server receives %40 or + where you had @ or a space. Encode the raw password once with a URL component encoder, then check it with libpq.
Can I avoid encoding the password in DATABASE_URL?
Only if your app accepts libpq's keyword and value format, where the password goes in single quotes with any quote or backslash escaped. A URL needs the encoding. Or choose a password of letters and digits only: 32 random ones hold about 190 bits, and nothing in the URL then needs encoding.
Next step
Run the check on the file that holds your app's DATABASE_URL. If the password comparison fails, rebuild the URL with pg-url.py make and load it with EnvironmentFile=.
New to running apps on your own server? How ox runs your apps shows what ox sets up on your server.
