Skip to content

Commit 19298bd

Browse files
Fix project-local PostgreSQL provisioning when the wizard runs as root
PostgreSQL refuses to run as root, but the setup wizard (and deploy.sh and PM2) commonly run as root on a dedicated server. Previously Step 3 aborted with the "run this as the unprivileged user" guard, and the same failure would recur at deploy (ctl-start) and at PM2 start time. - postgres-local.sh: when invoked as root, re-exec as the unprivileged owner of .postgres/ (from PG_RUN_USER for the first init, else the dir's owner) via runuser instead of failing. - ecosystem.config.cjs: PM2 drops to the cluster owner's uid/gid for the postgres process so it starts cleanly when PM2 runs as root. - setup-wizard.sh: determine/create a non-root app user, chown .postgres/ to it, and pass PG_RUN_USER so the first init hands off correctly.
1 parent d198430 commit 19298bd

3 files changed

Lines changed: 65 additions & 8 deletions

File tree

‎ecosystem.config.cjs‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,20 @@ const env = readEnv(path.join(root, '.env'));
4343
// If a project-local PostgreSQL cluster exists (created by scripts/postgres-local.sh on a
4444
// random port), let PM2 supervise it too, ahead of the API.
4545
const hasLocalPostgres = fs.existsSync(path.join(root, '.postgres', 'data', 'PG_VERSION'));
46+
47+
// PostgreSQL refuses to run as root. The cluster is owned by an unprivileged account (set up
48+
// by scripts/setup-wizard.sh); when PM2 itself runs as root we must drop to that account, or
49+
// `postgres-local.sh start` would refuse to launch. Derive the uid/gid from whoever owns the
50+
// cluster so this holds no matter which user it was created under.
51+
let localPostgresOwner = null;
52+
if (hasLocalPostgres) {
53+
try {
54+
const st = fs.statSync(path.join(root, '.postgres'));
55+
if (st.uid !== 0) localPostgresOwner = { uid: st.uid, gid: st.gid };
56+
} catch {
57+
/* fall back to inheriting PM2's own user */
58+
}
59+
}
4660
const localPostgresApp = {
4761
name: 'opencoperlock-postgres',
4862
cwd: root,
@@ -51,6 +65,8 @@ const localPostgresApp = {
5165
interpreter: 'bash',
5266
autorestart: true,
5367
max_restarts: 10,
68+
// Drop privileges to the cluster owner when PM2 runs as root (no-op if already that user).
69+
...(localPostgresOwner || {}),
5470
};
5571

5672
module.exports = {

‎scripts/postgres-local.sh‎

Lines changed: 23 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -16,19 +16,35 @@ set -euo pipefail
1616

1717
cd "$(dirname "$0")/.."
1818
ROOT="$(pwd)"
19-
20-
# PostgreSQL refuses to run as root, and the cluster should be owned by the app's run user.
21-
if [[ $EUID -eq 0 ]]; then
22-
echo "ERROR: run this as the unprivileged user that will own the database, not root." >&2
23-
echo " (The PM2 app user owns .postgres/; PostgreSQL will not start as root.)" >&2
24-
exit 1
25-
fi
2619
PGROOT="$ROOT/.postgres"
2720
DATA="$PGROOT/data"
2821
SOCK="$PGROOT/socket"
2922
PORT_FILE="$PGROOT/port"
3023
LOG="$PGROOT/postgres.log"
3124

25+
# PostgreSQL refuses to run as root, and the cluster must be owned by the app's run user.
26+
# When invoked as root — the wizard, deploy.sh and PM2 may all run as root — don't fail:
27+
# hand the cluster off to its unprivileged owner and re-exec. The target account comes from
28+
# $PG_RUN_USER (set by the wizard for the very first `init`, before .postgres/ exists) or,
29+
# once the cluster exists, from whoever owns .postgres/.
30+
if [[ $EUID -eq 0 ]]; then
31+
RUN_USER="${PG_RUN_USER:-}"
32+
if [[ -z "$RUN_USER" && -d "$PGROOT" ]]; then
33+
RUN_USER="$(stat -c '%U' "$PGROOT" 2>/dev/null || true)"
34+
fi
35+
if [[ -z "$RUN_USER" || "$RUN_USER" == root || "$RUN_USER" == UNKNOWN ]]; then
36+
echo "ERROR: refusing to run PostgreSQL as root, and no unprivileged owner is known." >&2
37+
echo " Set PG_RUN_USER=<user> (the account that will own .postgres/), or create" >&2
38+
echo " .postgres/ owned by that user first. The setup wizard does this for you." >&2
39+
exit 1
40+
fi
41+
command -v runuser >/dev/null 2>&1 || { echo "ERROR: 'runuser' not found (install util-linux)." >&2; exit 1; }
42+
# Re-exec the SAME command as the unprivileged user, carrying through the env `init` reads.
43+
exec runuser -u "$RUN_USER" -- env \
44+
DB_NAME="${DB_NAME:-}" DB_USER="${DB_USER:-}" DB_PASS="${DB_PASS:-}" \
45+
bash "$0" "$@"
46+
fi
47+
3248
# Locate the PostgreSQL server binaries. They are on PATH on most systems; on Debian/Ubuntu
3349
# they live under /usr/lib/postgresql/<version>/bin.
3450
find_pg_bin() {

‎scripts/setup-wizard.sh‎

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,15 @@ case "$DB_CHOICE" in
143143
[[ "$DB_NAME" =~ ^[A-Za-z_][A-Za-z0-9_]*$ ]] || die "Invalid database name (letters, digits, underscore)."
144144
[[ "$DB_USER" =~ ^[A-Za-z_][A-Za-z0-9_]*$ ]] || die "Invalid database user (letters, digits, underscore)."
145145
DB_PASS="$(openssl rand -hex 16)"
146+
# The project-local cluster must be OWNED and RUN by a non-root account (PostgreSQL — and
147+
# so PM2/deploy.sh while they supervise it — refuse to run as root). When the wizard runs
148+
# as root we need a separate account; otherwise the cluster belongs to the current user.
149+
if [[ $EUID -eq 0 ]]; then
150+
APP_USER="$(ask 'Unprivileged system user to own & run the database' "${SUDO_USER:-opencoperlock}")"
151+
[[ "$APP_USER" != root ]] || die 'The project-local database cannot be owned by root — pick another user.'
152+
else
153+
APP_USER="$(id -un)"
154+
fi
146155
# The port (and thus DATABASE_URL) is chosen at provisioning time (Step 3).
147156
;;
148157
2)
@@ -259,6 +268,18 @@ if [[ "$DB_PROVISION" != existing ]] && ! command -v initdb >/dev/null 2>&1 \
259268
fi
260269
fi
261270

271+
# A project-local cluster needs an unprivileged owner. When running as root, create the
272+
# account if it is missing so Step 3 (and later PM2) can drop privileges to it.
273+
if [[ "$DB_PROVISION" == local && $EUID -eq 0 ]] && ! id -u "$APP_USER" >/dev/null 2>&1; then
274+
if ask_yn "System user '$APP_USER' does not exist. Create it?" 'Y'; then
275+
useradd --system --create-home --shell /usr/sbin/nologin "$APP_USER" \
276+
|| die "Could not create system user '$APP_USER'."
277+
ok "Created system user '$APP_USER'"
278+
else
279+
die "Choose an existing unprivileged user for the project-local database, then re-run."
280+
fi
281+
fi
282+
262283
# nginx + certbot
263284
if $SETUP_NGINX && ! command -v nginx >/dev/null 2>&1 && [[ "$PKG" == apt ]]; then apt_install nginx; fi
264285
if $SETUP_TLS && ! command -v certbot >/dev/null 2>&1 && [[ "$PKG" == apt ]]; then apt_install certbot python3-certbot-nginx; fi
@@ -270,7 +291,11 @@ case "$DB_PROVISION" in
270291
local)
271292
say ""; info "Step 3 / 8 — Creating a project-local PostgreSQL (random port)"
272293
# postgres-local.sh must run as the unprivileged app user; it prints the DATABASE_URL.
273-
DATABASE_URL="$(DB_NAME="$DB_NAME" DB_USER="$DB_USER" DB_PASS="$DB_PASS" ./scripts/postgres-local.sh init)"
294+
# Pre-create .postgres/ owned by that account so a root wizard can hand the cluster off
295+
# (the script re-execs itself as PG_RUN_USER when invoked as root).
296+
mkdir -p "$ROOT_DIR/.postgres"
297+
[[ $EUID -eq 0 ]] && chown "$APP_USER:$(id -gn "$APP_USER")" "$ROOT_DIR/.postgres"
298+
DATABASE_URL="$(PG_RUN_USER="$APP_USER" DB_NAME="$DB_NAME" DB_USER="$DB_USER" DB_PASS="$DB_PASS" ./scripts/postgres-local.sh init)"
274299
[[ -n "$DATABASE_URL" ]] || die 'Project-local database provisioning failed.'
275300
ok "Project-local PostgreSQL ready (${DATABASE_URL##*@})"
276301
;;

0 commit comments

Comments
 (0)