Sub topic 6
Authenticating clients with auth_file and auth_query
This chapter assumes you can edit pgbouncer.ini (covered in the previous chapters), know how PostgreSQL roles and pg_hba.conf work, and understand the pool model: clients connect to PgBouncer, and PgBouncer opens server connections to PostgreSQL.
Two logins, not one
PgBouncer sits between two authentication steps:
- The client logs in to PgBouncer. PgBouncer must check the credentials itself, because no PostgreSQL backend is attached yet.
- PgBouncer logs in to PostgreSQL to open a server connection, using the same user name as the client.
Both steps need credentials. PgBouncer gets them from one of two places: a static file (auth_file) or a query run against PostgreSQL (auth_query). Both options let PgBouncer verify a password hash without storing plaintext passwords.
Choosing auth_type
auth_type controls how PgBouncer challenges the client.
| auth_type | Behavior |
|---|---|
| `scram-sha-256` | SCRAM challenge. Needs a SCRAM secret or plaintext password for the user. Recommended. |
| `md5` | MD5 challenge. If the user's entry is a SCRAM secret, PgBouncer uses SCRAM automatically. |
| `plain` | The client sends the password in clear text. Use only inside TLS. |
| `trust` | No password check. Only for isolated tests. |
| `cert` | Client TLS certificate identifies the user. |
| `hba` | Use a `pg_hba.conf`-style file named by `auth_hba_file`. |
Match auth_type to how the passwords are stored in PostgreSQL. Check password_encryption on the server. On PostgreSQL 14 and later it defaults to scram-sha-256. Older roles may still hold MD5 hashes until their passwords are reset.
Option 1: auth_file
auth_file points to a text file with one user per line: the user name and the password, each in double quotes.
"app_user" "SCRAM-SHA-256$4096:salt$storedkey:serverkey"
"report_user" "md5a1b2c3d4e5f60718293a4b5c6d7e8f9"You don't type these hashes by hand. Copy them from PostgreSQL. Run this as a superuser:
SELECT '"' || rolname || '" "' || rolpassword || '"'
FROM pg_authid
WHERE rolname = 'app_user';Append the output line to userlist.txt, then make PgBouncer re-read the file with RELOAD; on the admin console. Only pg_authid holds the hash, and only superusers can read it. Treat the file like a secret.
The file is simple and has no runtime dependency on PostgreSQL. It has two costs. You must update it every time a password changes, and every user must appear in it. With dozens of roles or frequent rotation, that becomes a maintenance burden.
Why hashes work for the server login too
PgBouncer must authenticate to PostgreSQL as the same role. There are three ways it can do that:
- With a plaintext password in
auth_file, PgBouncer answers whatever challenge the server sends. - With a SCRAM secret in
auth_file, PgBouncer can reuse the stored keys, but only if the client itself authenticated with SCRAM. This is a reason to avoid mixingplainormd5client logins with SCRAM-only servers. - With a
password=in the[databases]entry, PgBouncer logs in as a fixed user for every client. Then the client's user name is only checked at PgBouncer, and PostgreSQL sees one shared role.
Option 2: auth_query
auth_query has PgBouncer ask PostgreSQL for the hash at login time. PgBouncer runs the query as a dedicated role named by auth_user. A new user needs no change to PgBouncer, and password changes take effect immediately.
The default query reads pg_shadow, which only superusers can read. Giving PgBouncer a superuser login is a poor trade. Instead, create a low-privilege role and a SECURITY DEFINER function. The function runs with its owner's rights but exposes only one row per call.
CREATE ROLE pgbouncer_auth LOGIN PASSWORD 'change-me';
CREATE FUNCTION public.user_lookup(in i_username text, out uname text, out phash text)
RETURNS record AS $$
BEGIN
SELECT usename, passwd FROM pg_catalog.pg_shadow
WHERE usename = i_username INTO uname, phash;
RETURN;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
REVOKE ALL ON FUNCTION public.user_lookup(text) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION public.user_lookup(text) TO pgbouncer_auth;
-- In pgbouncer.ini, [pgbouncer] section:
-- auth_user = pgbouncer_auth
-- auth_query = SELECT uname, phash FROM public.user_lookup($1)Create the function as a superuser so that it can read pg_shadow. The REVOKE matters: PostgreSQL grants EXECUTE on new functions to PUBLIC by default, which would let any role fetch other users' hashes.
The full pgbouncer.ini then looks like this:
[databases]
appdb = host=127.0.0.1 port=5432 dbname=appdb
[pgbouncer]
listen_addr = 127.0.0.1
listen_port = 6432
auth_type = scram-sha-256
auth_file = /etc/pgbouncer/userlist.txt
auth_user = pgbouncer_auth
auth_query = SELECT uname, phash FROM public.user_lookup($1)
pool_mode = transaction
max_client_conn = 1000
default_pool_size = 20
admin_users = pgbouncer_adminHow the lookup is routed
PgBouncer checks auth_file first. If the user is listed there, it uses that entry. If not, and auth_user is set, it runs auth_query. This lets you keep a few special users, such as pgbouncer_auth itself and the admin user, in the file while the rest come from PostgreSQL.
The auth_user login itself needs a password PgBouncer knows. Put pgbouncer_auth in auth_file, or PgBouncer cannot connect to run the query.
The function must exist in the right database
By default, PgBouncer runs the lookup in the database the client asked for. The function then has to exist in every database you expose. If you have many databases, set auth_dbname to one database that holds the function:
auth_dbname = appdbYou can also set auth_user per database in the [databases] section to use different lookup roles for different databases.
Configure PostgreSQL to accept the connections
PostgreSQL's pg_hba.conf sees PgBouncer, not the original client, as the connecting host. You need entries for:
- the application roles, from the PgBouncer host address
pgbouncer_auth, for the lookup connection
# TYPE DATABASE USER ADDRESS METHOD
host appdb app_user 127.0.0.1/32 scram-sha-256
host appdb pgbouncer_auth 127.0.0.1/32 scram-sha-256Reload PostgreSQL after editing (SELECT pg_reload_conf();). Limit the address to the PgBouncer host rather than a broad range, since every client now appears to come from there.
Rotating passwords
The two options differ most during rotation.
- With
auth_file: change the password in PostgreSQL, regenerate the line, replace it inuserlist.txt, and runRELOAD;. Between the first and the last step, logins fail or succeed against stale hashes. - With
auth_query: change the password in PostgreSQL. The next login sees the new hash. Established server connections stay open, and existing clients stay connected.
Neither method disconnects clients already logged in. To force clients to re-authenticate, use KILL or DISABLE/ENABLE on the admin console.
Common errors
| Symptom | Likely cause |
|---|---|
| `no such user` in the PgBouncer log | User absent from `auth_file` and `auth_user` is not set |
| `password authentication failed` from the client | Hash in `auth_file` is stale, or `auth_type` does not match the hash type |
| `auth_user` lookup fails with `permission denied for function` | Missing `GRANT EXECUTE` on the function |
| Lookup works for one database, fails for another | Function missing in that database; set `auth_dbname` |
| `server login failed` after client login succeeds | `pg_hba.conf` does not allow the role from the PgBouncer host |
| Admin console login rejected | The admin user is not in `auth_file`, or is not listed in `admin_users` or `stats_users` |
Exercise
Your auth_type is scram-sha-256 and you use auth_query with auth_user = pgbouncer_auth. A new role report_user can log in to PostgreSQL directly, but a login through PgBouncer fails with a permission error from the lookup. The lookup function exists. Name two things to check and why you would not simply make pgbouncer_auth a superuser.
Show answer
Check that GRANT EXECUTE ON FUNCTION public.user_lookup(text) was given to pgbouncer_auth, and that the function exists in the database the client requested (or that auth_dbname points to one that has it). A superuser pgbouncer_auth would fix the symptom but give anyone who compromises PgBouncer's lookup login full control of the database. The SECURITY DEFINER function limits exposure to reading one user's hash per call.