Sub topic 5
How PostgreSQL picks a rule: first match wins
This chapter assumes you can read a pg_hba.conf record (type, database, user, address, method) and that you know basic CIDR notation. It covers how the server chooses one record for each incoming connection. Most surprising authentication behavior comes from this selection process, not from the methods themselves.
The rule: top to bottom, first match, no fallback
When a client connects, the server takes four facts about the connection and compares them with the records in pg_hba.conf, starting at the first line:
- Connection type: Unix socket, TCP without TLS, or TCP with TLS.
- Database: the database name the client asked for.
- User: the role name the client asked for.
- Client address: the IP address the server sees, which is relevant for TCP only.
The first record that matches all four is the only record used. PostgreSQL then runs that record's authentication method. There are two consequences:
- Later records are never consulted once one matches. A broad record placed early shadows every more specific record below it.
- A failed method does not fall through. If the matching record says
scram-sha-256and the password is wrong, the connection fails. The server does not try the next matching line.
If the server reaches the end of the file without a match, it rejects the connection. There is no implicit default allow. This end-of-file rejection is why the example file ends with an explicit reject rule: it makes the intent visible, and it produces a clear rule in pg_hba_file_rules.
A worked example
Here is the file from the chapter on SCRAM setup. Line numbers are added in comments for reference.
# TYPE DATABASE USER ADDRESS METHOD
local all postgres peer # line 2
local all all scram-sha-256 # line 3
host all all 127.0.0.1/32 scram-sha-256 # line 4
host all all ::1/128 scram-sha-256 # line 5
hostssl appdb app_user 10.0.0.0/24 scram-sha-256 # line 6
host all all 0.0.0.0/0 reject # line 7Now trace some connections through it.
| Connection | Matching line | Result |
|---|---|---|
| `psql -U postgres` over the Unix socket, OS user `postgres` | 2 | `peer` succeeds because the OS name equals the role name |
| `psql -U postgres` over the Unix socket, OS user `alice` | 2 | `peer` fails. Line 3 also matches, but is never tried |
| `psql -U app_user -d appdb` over the Unix socket | 3 | Password required (SCRAM) |
| `psql -h 127.0.0.1 -U app_user -d appdb` | 4 | Password required (SCRAM) |
| `app_user` to `appdb` from 10.0.0.5, TLS in use | 6 | Password required (SCRAM) |
| `app_user` to `appdb` from 10.0.0.5, no TLS | 7 | Rejected. Line 6 requires TLS, so it does not match |
| `app_user` to `appdb` from 192.168.1.9 | 7 | Rejected |
| `app_user` to `otherdb` from 10.0.0.5, TLS in use | 7 | Rejected. Line 6 names only `appdb` |
Two rows deserve attention. The second row shows that a more permissive later line does not rescue a failed peer check. The fifth and sixth rows show that the connection type is part of the match: the same client, user and database get a different outcome depending on whether TLS is in use. The hostssl keyword makes line 6 invisible to non-TLS connections, so they land on the reject rule.
What counts as a match in each field
The exact matching semantics matter when you read someone else's file.
Connection type
localmatches only Unix-domain socket connections.hostmatches any TCP/IP connection, with or without TLS.hostsslmatches TCP connections that use TLS.hostnosslmatches TCP connections that do not use TLS.
Because host matches both encrypted and unencrypted connections, a host line cannot enforce encryption. To force TLS for a network, use hostssl for the allowed range and a hostnossl ... reject line, or a final catch-all reject, so that unencrypted attempts are refused.
Database
- A name matches that database.
allmatches any database except replication connections.replicationmatches physical replication connections. It is not a database name.sameusermatches when the database name equals the role name.samerolematches when the role is a member of a role named like the database.- A comma-separated list matches any item. A name beginning with
+in the user field matches members of that role.
User
The user field accepts all, a role name, a +rolename (that role or any direct or indirect member), or a comma-separated list. Quote a name with double quotes if it would otherwise be read as a keyword.
Address
The address field accepts a CIDR range such as 10.0.0.0/24, a single host as /32 or /128, or an address plus a netmask in a separate column. It also accepts all, samehost, samenet, and host names. Host names are resolved with forward and reverse DNS lookups, so they are slow and depend on DNS you may not control. Prefer IP ranges.
The address is the one the server sees. Behind a load balancer or a connection pooler, that is the proxy's address, not the end client's. A rule written for the client network will not match.
Ordering strategy
Because the first match wins, order records from most specific to most general. A practical sequence is:
- Local administrative access (
peerfor the superuser). - Narrow, exceptional rules, such as one role from one subnet with TLS.
- General rules for normal users.
- A final explicit
rejectfor anything left over.
The following ordering is a common mistake:
# TYPE DATABASE USER ADDRESS METHOD
host all all 10.0.0.0/8 scram-sha-256
host appdb app_user 10.0.0.0/24 certThe second line can never be reached for traffic from 10.0.0.0/24, because the first line already matches every address in 10.0.0.0/8. app_user gets password authentication, not certificate authentication, and the file shows no error. Swap the two lines to get the intended behavior.
The danger is worst with trust. A line such as host all all 0.0.0.0/0 trust near the top of a file overrides all stricter rules beneath it. Do not use trust for network connections.
Checking order without guessing
The pg_hba_file_rules view lists the parsed rules in file order, with the line number of each, and an error column for lines that failed to parse. Use it after every edit.
SELECT pg_reload_conf();
SELECT line_number, type, database, user_name, address, auth_method, error
FROM pg_hba_file_rules
ORDER BY line_number;Note the following:
- The view reads the file on disk, not the rules currently in force. After an edit you can see the new content before reloading. Compare it with the active configuration by reloading and checking the server log.
- If the file contains a syntax error, the server keeps the previously loaded rules and logs the problem. A reload that "succeeded" can therefore leave old behavior in place. Always check the
errorcolumn for non-NULL values. - The view shows rules, not matches. It cannot tell you which rule a particular connection will hit. For that, trace the rows by hand as in the table above, or run a test connection.
Reading the rejection message
When no record matches, the client sees an error like this one:
FATAL: no pg_hba.conf entry for host "10.0.0.5", user "app_user", database "appdb", no encryptionThe message contains the four facts the server used: client address, role, database and encryption state. The exact wording of the encryption part varies by version (older releases print "SSL off" or "SSL on"). Compare these values with your rules. If the message says "no encryption" and your rule is hostssl, the rule cannot match.
Clients with sslmode=prefer, which is the libpq default, try TLS first and may fall back to plain TCP. You may then see two attempts in the server log, one for each encryption state, and the second can be the one that hits a reject. Set sslmode explicitly to make this predictable.
A different error, password authentication failed for user "app_user", means a record matched and the method ran and failed. That points at the password or its stored hash, not at the rule order.
Summary of key behaviors
- Each connection uses exactly one record, the first whose type, database, user and address all match.
- A failed method never falls through to a later record.
- No match means rejection.
- Put specific records above general ones, and end with an explicit
reject. - A
hostsslline is invisible to non-TLS connections, and ahostline cannot enforce encryption. - A reload with a parse error keeps the old rules. Check
pg_hba_file_rules.errorevery time.
Exercise
A file contains these records, in this order: host all all 10.1.0.0/16 scram-sha-256 host appdb reporter 10.1.2.0/24 reject The role reporter connects to appdb from 10.1.2.40 over TCP. Which record applies, what is the outcome if the password is correct, and how would you change the file so that reporter is blocked from that subnet?
Show answer
The first record applies, because 10.1.2.40 lies inside 10.1.0.0/16 and the type, database and user fields all match. With a correct password the connection succeeds. The reject record is never reached. To block reporter, put the more specific reject record above the broad scram-sha-256 record, then run pgreloadconf() and check pghbafile_rules for parse errors.
Exercise
With the six-line example file from this chapter, app_user connects to appdb from 10.0.0.5 using sslmode=disable. The log shows "no encryption". Which line handles the connection, and what is the result? What single change to the client would make the connection reach a password prompt?
Show answer
Line 6 (hostssl) does not match because the connection is not using TLS, so the server continues to line 7, host all all 0.0.0.0/0 reject, which matches and rejects the connection. If the client connects with TLS (for example sslmode=require or verify-full), line 6 matches and the server asks for a SCRAM password.