Goal: inspect authentication rules, prove password and first-match behavior with new connections, and restore the original policy while keeping an administrative connection open.
Connect as the SQL role postgres to the postgres database. Keep this administrative psql session open throughout the lab; we will test other logins without replacing it.
The lab has already created the role and database hba_demo, set its lesson-only password to lesson-secret, and saved the original HBA file as /tmp/hba-original.conf.
Save and display this connection’s identity:
pg_backend_pid() returns the ID of the server process handling this connection.
AS original_backend names the result column.
\gset executes the query and saves its single result row as psql variables named after the columns. It replaces the usual semicolon here and prints no result table.
\echo :original_backend displays the saved value. The colon means “substitute this psql variable.” Expect a positive integer; yours can differ from someone else’s.
This variable belongs to this psql client. Exiting and opening a new client loses it. We will compare it with the current PID in the final step.
Find the configuration file that this server uses, then identify how your current client connects.
SHOW hba_file returns the path we will edit. inet_client_addr() returns the client’s IP address for TCP connections and NULL for Unix-socket connections. The query turns that distinction into a boolean: t means true, so this connection uses TCP.
Even though we omitted -h, the lab shell supplies PGHOST=localhost. A host rule governs TCP, including localhost; a local rule means a Unix socket, not simply “a client on this computer.” Later tests use -h 127.0.0.1 explicitly to select IPv4 loopback.
Read the file in the order PostgreSQL would consider its rules. Expect six rows, all using trust.
rule_number is the rule’s order, not its physical file line number; comments and blank lines are skipped.
database and user_name are arrays. Braces such as {all} are their display format; all is an HBA matching keyword.
- A blank
address is expected for local rules, which have no IP-address field.
error IS NULL AS no_error gives t when that row parsed without error. It does not mean “authentication succeeded.”
This view reads the current file, including edits made before a reload. To prove the server is using a rule, we must also test a new connection.
Count rules whose authentication method is reject. Expect 0.
Notice the output still says (1 row): count(*) returns one summary row, and the value inside it says how many rules matched. Zero explicit rejects does not mean all possible connections are allowed; a connection that matches no HBA rule is also denied. We will add one narrow reject rule later.
Select only local rules. Expect two rows using trust, with no_error = t.
The first applies to ordinary database connections over Unix sockets. The {replication} entry is for physical replication connections, a special HBA category; it is not an ordinary database named replication. We are inspecting it, not starting replication.
These rows do not govern our TCP connection tests, even though those clients run on the same machine.
Count md5 rules: expect 0. Then establish a baseline by opening a new TCP connection as hba_demo. Expect the single line hba_demo; SELECT current_user identifies the SQL role that actually connected.
Read the longer command in pieces:
\! asks your current psql client to run a shell command. The nested psql starts a separate connection, runs its query, exits, and returns you to the original postgres=# prompt.
PGPASSWORD= clears the password environment value for this command. PGCONNECT_TIMEOUT=3 bounds connection establishment to three seconds.
-w prevents a password prompt; it does not bypass authentication. Under a password rule, this test will fail rather than wait for input.
-h 127.0.0.1 chooses IPv4 loopback; -U hba_demo chooses the SQL role and -d hba_demo chooses the database.
-Atc combines -A (unaligned output), -t (values without headings/footers), and -c (execute the quoted SQL, then exit).
The login succeeds here because the matching trust rule does not check a password.
Change the IPv4 loopback trust rules to scram-sha-256, then compare two new logins. The demo role already has a SCRAM password from the lab setup; editing HBA chooses an authentication method, but does not create or change that password.
What each action does:
\! runs the file edit in a shell. as-postgres selects the Linux file owner; this is separate from the SQL role in your open connection.
sed -i edits the file in place. The pattern selects lines starting with host, containing 127.0.0.1, and ending in trust; the substitution replaces only that final method. Escaped dots match literal dots; .* matches intervening text. Both matching IPv4 entries change, including the replication entry; IPv6 and socket rules remain as they were.
pg_reload_conf() requests a reload. Its t acknowledges sending the signal. pg_sleep(0.1) gives the server a brief moment to process it; the connection tests establish the result.
- The no-password test must fail with
fe_sendauth: no password supplied.
- The otherwise identical test with
PGPASSWORD=lesson-secret must print hba_demo. This value applies only to that child command.
These two results show that a password is now required and that the configured password works. Your original administrative connection stays open.
Put a narrow reject before the broader SCRAM rule, then test before reloading. Predict the result: the file will show the reject, but a new password login will still succeed under the previously loaded policy.
The added HBA line has five fields: host (TCP), hba_demo (database), hba_demo (role), 127.0.0.1/32 (this one IPv4 address), and reject (deny). The two identical names fill different fields.
How the file command prepends a line:
as-postgres sh -c '…' runs the whole quoted script as the Linux owner, including its redirection.
umask 077 requests owner-only permissions when creating the temporary file.
printf "%s\n" writes the new rule and a newline; cat then writes the existing file. Braces group both outputs, and > writes them into a temporary file.
&& mv replaces the HBA file only if writing the temporary file succeeded. Writing directly over the input file would truncate it before cat read it.
The SQL filter uses ARRAY['hba_demo'] because database is an array. Expect one reject row with no_error = t, followed by a successful hba_demo login. Do not reload yet.
Now reload, wait briefly, and retry the same password login used in the previous step. This time expect pg_hba.conf rejects connection for hba_demo.
The password did not change. The loaded rule order did: the narrow first rule selects reject, so PostgreSQL denies the connection without trying the later SCRAM rule. A correct password cannot override a reject.
The error is the intended result of this experiment. no encryption in its detail describes the attempted connection; this reject rule blocks the matched connection regardless of whether it is encrypted. When the child client exits, you return to your still-open administrative prompt.
Restore the policy we started with, reload it, and test a new login without a password.
cp reads /tmp/hba-original.conf, saved automatically before the exercise, and replaces the edited HBA file. A successful copy normally prints nothing.
- Reload is still needed: replacing a file alone does not replace the server’s loaded rules.
count(*) FILTER (WHERE …) counts only rows meeting that condition. Expect parse_errors = 0 and demo_rules = 0; the second count checks HBA entries naming the demo database, not whether its SQL role/database exists.
- The final no-password test must print
hba_demo again, showing that the original loopback trust behavior is restored.
Restoring the HBA file leaves the demo role and its password in place. It changes the connection policy back to the lab baseline.
Check whether the original administrative connection survived every reload. Expect current_user = postgres and same_backend = t.
Before PostgreSQL receives this query, psql replaces :original_backend with the numeric value saved by \gset in step 1. pg_backend_pid() obtains this connection’s current server-process ID; = compares the two values, and AS same_backend labels the boolean result.
An HBA reload changes authentication decisions for new connections. It does not reauthenticate or disconnect an already established session. Our temporary test clients connected and exited separately, leaving this client and its saved variable intact.
If you exited psql during the exercise, the variable is lost. A syntax error at : means psql could not substitute it; repeat the lab from step 1 to make a valid before/after comparison.