#!/usr/bin/env bash
# Published with the Tabellum blog article "no pg_hba.conf entry for host ..., no encryption" (tabellum.dudko.dev/blog).
# "no pg_hba.conf entry for host ..., no encryption": what each libpq sslmode does against a
# PostgreSQL server that only accepts TLS (hostssl lines only, the way managed services set it up),
# and against a server with TLS switched off.
# Needs: PostgreSQL server binaries (initdb, pg_ctl, postgres) and psql, openssl.
#   PGBIN=/usr/lib/postgresql/16/bin ./measure.sh
# Or with Docker only (psql cases; run it from this folder):
#   docker run --rm -v "$PWD":/m:ro -e PGBIN=/usr/lib/postgresql/18/bin postgres:18 bash /m/measure.sh
# With node-postgres too: NODE_PG_DIR=<a folder where `npm install pg` ran> ./measure.sh
# Run as root it starts the server as the "postgres" OS user; otherwise as you.
set -u
HERE=$(cd "$(dirname "$0")" && pwd)
PGBIN=${PGBIN:-/usr/lib/postgresql/16/bin}
PORT=${PORT:-55432}
W=$(mktemp -d /tmp/pgssl.XXXXXX); chmod 755 "$W"
AS=""; [ "$(id -u)" = 0 ] && { chown postgres "$W"; AS="runuser -u postgres --"; }
cd "$W"

# 1. A private CA and a server certificate for the names "localhost" and "db.example.com"
#    (no IP address in subjectAltName).
openssl req -x509 -newkey rsa:2048 -nodes -days 2 -subj "/CN=test-ca" \
  -keyout ca.key -out ca.crt 2>/dev/null
openssl req -newkey rsa:2048 -nodes -subj "/CN=localhost" \
  -keyout server.key -out server.csr 2>/dev/null
printf 'subjectAltName=DNS:localhost,DNS:db.example.com\n' > san.ext
openssl x509 -req -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial -days 2 \
  -extfile san.ext -out server.crt 2>/dev/null
# A second, unrelated CA: what a client has when it was given the wrong root certificate.
openssl req -x509 -newkey rsa:2048 -nodes -days 2 -subj "/CN=other-ca" \
  -keyout other.key -out other-ca.crt 2>/dev/null
chmod 600 server.key; [ -n "$AS" ] && chown postgres server.key server.crt ca.crt

# 2. A cluster that accepts TCP connections over TLS only.
$AS "$PGBIN/initdb" -D "$W/data" -U postgres --auth-local=trust --auth-host=scram-sha-256 >/dev/null
printf 'hostssl all postgres 127.0.0.1/32 scram-sha-256\nhostssl all postgres ::1/128 scram-sha-256\nlocal all all trust\n' \
  > "$W/data/pg_hba.conf"
cat >> "$W/data/postgresql.conf" <<EOF
port = $PORT
listen_addresses = 'localhost'
unix_socket_directories = '$W'
ssl = on
ssl_cert_file = '$W/server.crt'
ssl_key_file = '$W/server.key'
EOF
[ -n "$AS" ] && chown postgres "$W/data/pg_hba.conf"
start(){ $AS "$PGBIN/pg_ctl" -D "$W/data" -l "$W/log" -w start >/dev/null; }
stop(){ $AS "$PGBIN/pg_ctl" -D "$W/data" -w stop >/dev/null; }
start
$AS "$PGBIN/psql" -h "$W" -p $PORT -U postgres -qAtc "ALTER USER postgres PASSWORD 'pw'"
echo "server: $($AS "$PGBIN/psql" -h "$W" -p $PORT -U postgres -Atc 'select version()')"
echo "client: $(psql --version)  ($(openssl version))"

try(){  # label, then extra conninfo
  local label=$1; shift
  out=$(PGPASSWORD=pw PGCONNECT_TIMEOUT=5 psql "port=$PORT user=postgres dbname=postgres $*" -XAtc \
    "select coalesce((select 'TLS '||version||' '||cipher from pg_stat_ssl where pid=pg_backend_pid() and ssl),'no TLS')" 2>&1 | tr '\n' ' ')
  printf '%-44s | %s\n' "$label" "$out"
}
run_cases(){
  try "disable"                         "host=localhost sslmode=disable"
  try "allow"                           "host=localhost sslmode=allow"
  try "prefer (libpq default)"          "host=localhost sslmode=prefer"
  try "require"                         "host=localhost sslmode=require"
  try "verify-ca, no root cert"         "host=localhost sslmode=verify-ca sslrootcert=$W/none.crt"
  try "verify-ca, right CA"             "host=localhost sslmode=verify-ca sslrootcert=$W/ca.crt"
  try "verify-ca, wrong CA"             "host=localhost sslmode=verify-ca sslrootcert=$W/other-ca.crt"
  try "verify-full, right CA, localhost" "host=localhost sslmode=verify-full sslrootcert=$W/ca.crt"
  try "verify-full, right CA, 127.0.0.1" "host=127.0.0.1 sslmode=verify-full sslrootcert=$W/ca.crt"
  try "verify-full, tunnel style (hostaddr)"  "host=db.example.com hostaddr=127.0.0.1 sslmode=verify-full sslrootcert=$W/ca.crt"
  try "verify-full, sslrootcert=system"  "host=localhost sslmode=verify-full sslrootcert=system"
  try "require + sslrootcert=right CA"  "host=localhost sslmode=require sslrootcert=$W/ca.crt"
  try "require + sslrootcert=wrong CA"  "host=localhost sslmode=require sslrootcert=$W/other-ca.crt"
  try "require, a user no line matches"   "host=localhost sslmode=require user=nobody"
}
echo; echo "== A. ssl = on, pg_hba.conf has hostssl lines only"
run_cases
# Optional: the same server through node-postgres. NODE_PG_DIR = a folder where `npm install pg` ran.
if [ -n "${NODE_PG_DIR:-}" ]; then
  echo; echo "== A2. same server, node-postgres"
  node "$HERE/node-pg.mjs" $PORT "$W" "$NODE_PG_DIR" 2>&1
fi

echo; echo "== B. ssl = off (server not configured for TLS), pg_hba.conf host lines"
stop
sed -i 's/^ssl = on/ssl = off/' "$W/data/postgresql.conf"
sed -i 's/^hostssl/host/' "$W/data/pg_hba.conf"
start
run_cases

stop; rm -rf "$W"
