Validate PostgreSQL SCRAM Authentication and HBA Rule Order

Validate PostgreSQL SCRAM Authentication and HBA Rule Order

Validate PostgreSQL SCRAM Authentication and HBA Rule Order

After migrating a database to a dedicated server, a successful application connection is only the first check. If an older, broader rule appears first, a new restriction may never be matched. If tests keep reusing pooled connections, the updated authentication policy may never be tested at all. Acceptance testing must demonstrate all three outcomes: permitted connections succeed, incorrect passwords fail, and unauthorized roles are rejected.

This guide uses Debian 12 and PostgreSQL 15 to create an isolated instance that listens only on the loopback address, without changing the production database. Users manage the system and data on HttpAmd dedicated servers; after payment, view the connection credentials in the control panel and access the system over SSH. This lab requires no additional public IP address, and the database should not be temporarily exposed to the public internet.

1. Define the instance and credential boundaries

The lab requires the PostgreSQL 15 server tools to be installed. Run the commands as the system's postgres account. First, verify the binary paths and check that the lab port is not in use. If something is already listening, choose an unused port and update the subsequent commands accordingly. The port 55432 is chosen for this lab, not supplied as a provisioning parameter.

sudo -iu postgres
export PATH=/usr/lib/postgresql/15/bin:$PATH
command -v initdb pg_ctl psql
ss -ltn 'sport = :55432'
export LAB="$(mktemp -d /var/tmp/pg-hba-lab.XXXXXX)"
printf '%s\n' "$LAB"
initdb -D "$LAB/data" --auth-local=peer --auth-host=scram-sha-256
pg_ctl -D "$LAB/data" -l "$LAB/server.log" \
  -o "-p 55432 -k $LAB -c listen_addresses=127.0.0.1" start

Record the printed lab directory and run all subsequent commands in the same terminal. The directory created by mktemp is accessible only to the current account, preventing other local accounts from reading the lab data. If startup fails, check the log in that directory first; do not switch to starting the system-managed production instance.

Keep the local administration path authenticated through the operating system identity while testing TCP password authentication. Testing a restriction must not begin by cutting off every administrative access path.

2. Create roles and set a SCRAM password

Unix sockets and TCP are separate connection paths. Use the socket in the lab directory to administer this instance and avoid accidentally connecting to the production database. The -X option prevents psql from reading personal startup files, reducing interference from hidden settings.

psql -X -h "$LAB" -p 55432 -U postgres -d postgres

In the interactive session, run:

CREATE ROLE lab_login LOGIN;
CREATE ROLE lab_blocked LOGIN;
CREATE DATABASE lab_auth;
SET password_encryption = 'scram-sha-256';
\password lab_login

Enter a password used only for this lab when prompted. Then check the stored format without displaying the full password verifier:

SELECT rolname,
       rolpassword LIKE 'SCRAM-SHA-256$%' AS uses_scram
FROM pg_authid
WHERE rolname = 'lab_login';
\q

uses_scram should be true. Changing password_encryption does not rewrite existing passwords; it affects only passwords set afterward. The interactive \password command avoids placing a plaintext password directly in a shell command or SQL history. Do not reuse production credentials for the lab.

The sole purpose of lab_blocked is to demonstrate that HBA rejects unauthorized roles, so it does not need a password. Both roles have the login attribute, ensuring that rejection is not confused with a role being unable to log in.

3. Write minimal HBA rules and check parsing

HBA processes rules in file order and selects the first rule matching the connection type, database, role, and source address. Once an authentication rule is selected, authentication failure does not cause PostgreSQL to try a later rule that might allow access.

cp "$LAB/data/pg_hba.conf" "$LAB/pg_hba.before"

cat > "$LAB/data/pg_hba.conf" <<'EOF'
local all postgres peer
host lab_auth lab_login 127.0.0.1/32 scram-sha-256
host all all 127.0.0.1/32 reject
EOF

psql -X -h "$LAB" -p 55432 -U postgres -d postgres <<'SQL'
SELECT line_number, type, database, user_name,
       address, auth_method, error
FROM pg_hba_file_rules
ORDER BY line_number;
SELECT pg_reload_conf();
SQL

First confirm that error is empty for every row, then inspect the reload result and logs. This view reads the current configuration file and can reveal parsing problems, but it cannot by itself prove that the running instance is using the new rules for connections. A true result from pg_reload_conf() means only that the signal was sent.

There is no rule allowing IPv6. The instance explicitly listens only on 127.0.0.1, so use that address consistently for testing rather than a hostname that might resolve to a different address family. SCRAM provides password authentication; it does not mean the connection is encrypted. Future connections between hosts will require separate planning for TLS and permitted source ranges.

4. Test allowed and rejected access with fresh connections

Start a new psql process for every test rather than using a connection pool. Clear environment variables that could supply a password or service configuration, and disable the password file so the results reflect only the current input and explicitly specified parameters.

unset PGPASSWORD PGSERVICE PGSERVICEFILE
export PGPASSFILE=/dev/null

psql -X -h 127.0.0.1 -p 55432 -U lab_login \
  -d lab_auth -W -c 'SELECT current_user, current_database();'
printf 'exit=%s\n' "$?"

Enter the correct password on the first attempt. The query should return lab_login and lab_auth, with an exit code of zero. Run the same command again and enter an incorrect password. It should report a password authentication failure and return a nonzero exit code. A client password prompt alone is not evidence of successful authentication.

Next, test the unauthorized role:

psql -X -h 127.0.0.1 -p 55432 -U lab_blocked \
  -d lab_auth -w -c 'SELECT 1;'
printf 'exit=%s\n' "$?"

Here, -w disables interactive password prompts. The expected result is an explicit HBA rejection—not a successful query and not a failure caused by a missing password. Finally, test the permitted role again with the database changed to postgres. The catch-all rejection rule should deny this connection too, proving that permission does not extend to other databases.

Save the commands, exit codes, and error categories, but do not record passwords or complete password verifiers. When a connection is rejected, do not change the rule to trust just to “test the network.” Doing so bypasses the authentication boundary this lab is meant to verify.

5. Verify rule-order effects and complete the rollback

In this isolated instance, back up the current three-line rule set, then move the loopback reject line above the allow line. Check parsing again, send the reload signal, and open a fresh connection using the correct password. It should now be rejected as well. This counterexample demonstrates that an allow rule farther down the file cannot override an earlier rejection.

The socket-based administration path retained throughout the lab is unaffected by the order of these two TCP rules. Restore the file, reload it again, and rerun the three tests: correct password, incorrect password, and unauthorized role.

psql -X -h "$LAB" -p 55432 -U postgres -d postgres \
  -c 'SELECT pg_reload_conf();'
tail -n 40 "$LAB/server.log"

Acceptance criteria for production changes

Before applying changes in production, inventory the actual client versions, source addresses, roles, and database scope. Verify that the clients support SCRAM, then schedule password updates. Successful authentication does not grant table privileges. Validate authorization separately rather than widening HBA access to eliminate permission errors.

The checks should confirm that rules have no parsing errors, fresh connections follow the intended rule path, incorrect passwords cannot fall through to another rule, unauthorized roles and databases are rejected, and the previous file can be restored. Existing sessions do not automatically reauthenticate after a reload. Revoking access therefore also requires assessing existing connections, not merely confirming that new connections fail.

Finally, stop the lab instance. Confirm that it has stopped successfully before removing the directory at the exact path recorded earlier:

pg_ctl -D "$LAB/data" -m fast stop

Retain a sanitized acceptance-test record, then delete the lab data. A complete authentication change should leave evidence of both allowed and rejected access, along with repeatable rollback steps.

Frequently asked questions

Does changing password_encryption convert existing roles to SCRAM?

No. It affects passwords set afterward, not existing password verifiers. Check client compatibility, reset the affected role passwords, and verify actual connections.

Does true from pg_reload_conf() prove that the rules are active?

No. It confirms that the reload signal was sent. Check parsing errors, server logs and fresh connections. Existing sessions are not authenticated again.

AMD EPYC 7543P Dedicated Server

HttpAmd From $470.5/month

Review the server specifications

Compare the memory, direct-attached NVMe, bandwidth, and IPv4 specifications, then confirm the amount due for the current billing period on the configuration page.