#!/bin/sh
# Measurements for "FATAL: Peer authentication failed for user ..." (SQLSTATE 28000).
#
# Starts one container with PostgreSQL from the distribution package (Debian 12
# by default, or Ubuntu 24.04), where the default pg_hba.conf has
# "local ... peer", and one official postgres image for comparison, where it has
# "local ... trust". Prints every client message and the server log lines that go
# with it. Needs only Docker; the containers are removed at the end (KEEP=1 keeps
# them). The passwords "dummy" are test values.
#
#   ./run.sh 2>&1 | tee results.txt
#   IMAGE=ubuntu:24.04 ./run.sh 2>&1 | tee results-ubuntu.txt
set -u
PREFIX=${PREFIX:-peer}
IMAGE=${IMAGE:-debian:bookworm}
OFFICIAL=${OFFICIAL:-postgres:17}
D="$PREFIX-pkg"
O="$PREFIX-official"

section() { echo; echo "=================== $*"; date -u '+%Y-%m-%d %H:%M:%S UTC'; }
x() { docker exec "$D" sh -c "$1" 2>&1; echo "[exit $?]"; }   # run as root in the package container
as() { u=$1; shift; docker exec -u "$u" "$D" sh -c "$1" 2>&1; echo "[exit $?]"; }  # run as OS user $u
logtail() { docker exec "$D" sh -c "tail -n ${1:-3} $LOG"; }
reload() { docker exec -u postgres "$D" psql -XAtc 'select pg_reload_conf()'; sleep 0.5; }
cleanup() { [ "${KEEP:-0}" = 1 ] || docker rm -f "$D" "$O" >/dev/null 2>&1; }
trap cleanup EXIT

docker rm -f "$D" "$O" >/dev/null 2>&1
docker run -d --name "$D" "$IMAGE" sleep infinity >/dev/null
docker run -d --name "$O" -e POSTGRES_PASSWORD=dummy "$OFFICIAL" >/dev/null

echo "installing postgresql from the $IMAGE package (takes a minute)..."
docker exec "$D" sh -c 'export DEBIAN_FRONTEND=noninteractive;
  apt-get update -qq && apt-get install -y -qq postgresql sudo python3-psycopg2 >/dev/null 2>&1'
V=$(docker exec "$D" sh -c 'ls /etc/postgresql | sort -n | tail -1')
HBA=/etc/postgresql/$V/main/pg_hba.conf
IDENT=/etc/postgresql/$V/main/pg_ident.conf
LOG=/var/log/postgresql/postgresql-$V-main.log
docker exec "$D" pg_ctlcluster "$V" main start
docker exec "$D" sh -c 'useradd -m app; useradd -m alice'
until docker exec "$O" pg_isready -U postgres -h 127.0.0.1 -q 2>/dev/null; do sleep 1; done

section "0. versions and the default pg_hba.conf"
docker exec -u postgres "$D" psql -XAtc 'select version()'
docker exec "$D" psql --version
docker exec "$D" sh -c "grep -nEv '^(#|\$)' $HBA"
echo "-- official image $OFFICIAL:"
docker exec "$O" psql -U postgres -XAtc 'select version()'
docker exec "$O" sh -c 'grep -Ev "^(#|$)" "$PGDATA/pg_hba.conf"'

section "1. psql -U postgres as root, as app, as alice (socket, local ... peer)"
x 'psql -U postgres -c "select 1"'
as app 'psql -U postgres -c "select 1"'
as alice 'psql -U postgres -d postgres -c "select 1"'
echo "-- server log:"; logtail 9

section "1b. psql as root without -U"
x 'psql -c "select 1"'
logtail 1

section "1c. a role that does not exist, over peer; role root asked by alice; -h with the socket directory"
as alice 'psql -U nobody -d postgres -Xc "select 1"'
logtail 3
as alice 'psql -U root -d postgres -Xc "select 1"'
logtail 3
x 'psql -h /var/run/postgresql -U postgres -c "select 1"'

section "2. the same, with -h localhost / -h 127.0.0.1 (role postgres has no password yet)"
x 'psql -U postgres -h localhost -c "select 1" </dev/null'
x 'psql -U postgres -h 127.0.0.1 -w -c "select 1"'
echo "-- server log (expect nothing new):"; logtail 1
x 'PGPASSWORD=wrong psql -U postgres -h localhost -c "select 1"'
logtail 3
echo "-- sslmode=disable: one attempt instead of two"
x 'PGPASSWORD=wrong psql "sslmode=disable host=localhost user=postgres" -c "select 1"'
echo "-- sslmode=require: also one attempt"
x 'PGPASSWORD=wrong psql "sslmode=require host=localhost user=postgres" -c "select 1"'
docker exec -u postgres "$D" psql -Xqc "alter role postgres password 'dummy'"
echo "-- after: alter role postgres password 'dummy'"
x 'PGPASSWORD=dummy psql -U postgres -h 127.0.0.1 -c "select current_user, inet_client_addr()"'
x 'PGPASSWORD=wrong psql "sslmode=disable host=localhost user=postgres" -c "select 1"'
logtail 2

section "3. sudo -u postgres psql"
x 'sudo -u postgres psql -c "select current_user, inet_client_addr() is null as via_socket"'

section "4. pg_ident.conf: OS user app -> role appuser"
docker exec -u postgres "$D" psql -Xq -c "create role appuser login password 'dummy'" -c 'create database appdb owner appuser'
echo "-- without a map:"
as app 'psql -U appuser -d appdb -c "select current_user"'
logtail 3
docker exec "$D" sed -i 's/^local   all             all                                     peer$/local   appdb           appuser                                 peer map=appmap\n&/' "$HBA"
docker exec "$D" sh -c "echo 'appmap          app                     appuser' >> $IDENT"
docker exec "$D" sh -c "grep -nEv '^(#|\$)' $HBA | grep local; grep -nEv '^(#|\$)' $IDENT"
reload
echo "-- with the map, after a reload:"
as app 'psql -U appuser -d appdb -c "select current_user, session_user"'
echo "-- another OS user on the same line:"
as alice 'psql -U appuser -d appdb -c "select 1"'
logtail 3
echo "-- the map works, the role does not exist: app -> ghost"
docker exec "$D" sed -i 's/^local   appdb           appuser                                 peer map=appmap$/local   appdb           appuser,ghost                           peer map=appmap/' "$HBA"
docker exec "$D" sh -c "echo 'appmap          app                     ghost' >> $IDENT"; reload
as app 'psql -U ghost -d appdb -c "select 1"'
logtail 1
docker exec "$D" sed -i 's/appuser,ghost                           peer/appuser                                 peer/' "$HBA"
docker exec "$D" sed -i '/ghost$/d' "$IDENT"; reload
echo "-- typo 1: map=appmpa in pg_hba.conf"
docker exec "$D" sed -i 's/map=appmap/map=appmpa/' "$HBA"; reload
docker exec -u postgres "$D" psql -Xc "select line_number, database, user_name, auth_method, options, error from pg_hba_file_rules where 'map=appmpa' = any(options)"
as app 'psql -U appuser -d appdb -c "select 1"'
logtail 3
docker exec "$D" sed -i 's/map=appmpa/map=appmap/' "$HBA"
echo "-- typo 2: system user 'ap' in pg_ident.conf"
docker exec "$D" sed -i 's/^appmap          app /appmap          ap  /' "$IDENT"; reload
docker exec -u postgres "$D" psql -Xc 'select line_number, map_name, sys_name, pg_username, error from pg_ident_file_mappings'
as app 'psql -U appuser -d appdb -c "select 1"'
logtail 3
docker exec "$D" sed -i 's/^appmap          ap  /appmap          app /' "$IDENT"; reload

section "5. editing pg_hba.conf without a reload, and a typo at reload"
echo "-- official image: local all all trust -> peer, no reload"
docker exec "$O" sh -c 'sed -i "s/^local   all             all                                     trust$/local   all             all                                     peer/" "$PGDATA/pg_hba.conf"'
docker exec "$O" sh -c 'psql -U postgres -XAtc "select 1"' 2>&1
docker exec -u postgres "$O" psql -XAtc "select line_number, type, database, user_name, auth_method from pg_hba_file_rules where type = 'local'"
docker exec -u postgres "$O" psql -XAtc 'select pg_reload_conf()'; sleep 0.5
echo "-- after the reload, the same root psql:"
docker exec "$O" psql -U postgres -XAtc 'select 1' 2>&1
echo "-- and TCP to 127.0.0.1 (host ... trust), no password:"
docker exec "$O" psql -U postgres -h 127.0.0.1 -w -XAtc "select 'connected via ' || host(inet_client_addr())" 2>&1
echo "-- package: typo 'peeer' in the map line, reload"
docker exec "$D" sed -i 's/peer map=appmap/peeer map=appmap/' "$HBA"
reload
docker exec -u postgres "$D" psql -Xc 'select line_number, auth_method, error from pg_hba_file_rules where error is not null'
logtail 3
as app 'psql -U appuser -d appdb -XAtc "select current_user"'
docker exec "$D" sed -i 's/peeer map=appmap/peer map=appmap/' "$HBA"; reload
echo "-- package: 'ident' instead of 'peer' on the local all all line, reload"
docker exec "$D" sed -i 's/^local   all             all                                     peer$/local   all             all                                     ident/' "$HBA"
reload
docker exec -u postgres "$D" psql -XAtc "select line_number, type, auth_method from pg_hba_file_rules where type = 'local'"
as alice 'psql -U nobody -d postgres -c "select 1"'
logtail 3
docker exec "$D" sed -i 's/^\(local   all             all                                     \)ident$/\1peer/' "$HBA"; reload

section "6. psycopg2 (libpq): no host means the socket, and a password does not help"
docker exec -i -u alice "$D" python3 - <<'EOF'
import os, psycopg2
cases = [
    dict(dbname='appdb', user='appuser'),
    dict(dbname='appdb', user='appuser', host=''),
    dict(dbname='appdb', user='appuser', password='dummy'),
    dict(dbname='appdb', user='appuser', host='localhost'),
    dict(dbname='appdb', user='appuser', host='localhost', password='dummy'),
]
print('psycopg2', psycopg2.__version__, 'libpq', psycopg2.__libpq_version__)
for kw in cases:
    try:
        c = psycopg2.connect(**kw)
        cur = c.cursor(); cur.execute('select current_user, inet_client_addr()')
        print(kw, '\n  OK', cur.fetchone())
    except Exception as e:
        print(kw, '\n ', type(e).__name__ + ':', str(e).strip())
os.environ['PGHOST'] = ''
kw = dict(dbname='appdb', user='appuser', password='dummy')
try:
    psycopg2.connect(**kw); print("PGHOST='' +", kw, '\n  OK')
except Exception as e:
    print("PGHOST='' +", kw, '\n ', type(e).__name__ + ':', str(e).strip())
EOF
echo "-- psql with an empty PGHOST, and with a ~/.pgpass entry for appuser (socket)"
as alice 'PGHOST= psql -U appuser -d appdb -c "select 1"'
as alice 'printf "*:*:*:appuser:dummy\n" > "$HOME/.pgpass"; chmod 600 "$HOME/.pgpass"; psql -U appuser -d appdb -c "select 1"; e=$?; rm "$HOME/.pgpass"; exit $e'

section "7. the client message is the same in the official image (local ... peer from section 5)"
docker exec "$O" psql -U postgres -XAtc 'select 1' 2>&1
docker logs "$O" 2>&1 | grep -E 'do not match|Peer|DETAIL' | tail -3
