Skip to content

🛡️ Warracker is an open source, self-hostable warranty tracker to monitor expirations, store receipts, files. You own the data, your rules!

Make DB_ADMIN_USER and DB_ADMIN_PASSWORD optional with no defaults (#221)

sassanix40cbac95151f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 70a099b..8ac4eb4 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,8 +2,8 @@
## 1.0.7 - Unreleased
-- **Database credential defaults removed (#221, by Nam0101):** the built-in defaults for `DB_USER`, `DB_PASSWORD`, `DB_ADMIN_USER`, and `DB_ADMIN_PASSWORD` are gone, completing the deprecation announced in 1.0.5. The app, the migration runner, and the permissions script now stop with a clear message naming any missing variable instead of falling back to known credentials. `DATABASE_URL` still works as before: a URL containing a username and password supplies the app credentials, and the two admin variables remain required because migrations use them. Both shipped Docker Compose files, the env examples, and the Unraid template set all four explicitly, so installs that follow them need no action. The Unraid template also no longer prefills a default admin password.
- - _Files: `backend/config.py`, `backend/db_handler.py`, `backend/fix_permissions.py`, `backend/migrations/apply_migrations.py`, `Docker/entrypoint.sh`, `env.example`, `unraid/warracker.xml`, `tests/conftest.py`, `.github/workflows/tests.yml`, `tests/test_db_credentials_required.py`_
+- **Database credential defaults removed (#221, by Nam0101):** the built-in defaults for `DB_USER`, `DB_PASSWORD`, `DB_ADMIN_USER`, and `DB_ADMIN_PASSWORD` are gone, completing the deprecation announced in 1.0.5. The app, the migration runner, and the permissions script now stop with a clear message naming any missing required credential instead of falling back to known credentials. `DB_USER` and `DB_PASSWORD` (or a `DATABASE_URL` containing a username and password) are required. `DB_ADMIN_USER` and `DB_ADMIN_PASSWORD` are optional with no built-in defaults: if both are omitted, existing installs upgrade without adding unused variables and fresh installs skip creating the optional PostgreSQL admin role in `010_configure_admin_roles.sql`; if only one is set, startup stops naming the missing counterpart so no role is ever created with a blank or default password. The Unraid template marks both admin variables optional with no prefilled defaults.
+ - _Files: `backend/config.py`, `backend/db_handler.py`, `backend/fix_permissions.py`, `backend/migrations/apply_migrations.py`, `backend/migrations/010_configure_admin_roles.sql`, `Docker/entrypoint.sh`, `env.example`, `Docker/.env.example`, `unraid/warracker.xml`, `tests/conftest.py`, `.github/workflows/tests.yml`, `tests/test_db_credentials_required.py`_
- **PKCE (S256) for OIDC sign-in (#288, suggested by John in Discord):** the OIDC authorization code flow now uses PKCE when the identity provider supports it. At startup Warracker reads the provider discovery document, and if it advertises S256 in `code_challenge_methods_supported`, the client is registered with PKCE enabled, so the authorization code is bound to a verifier only Warracker holds. Providers that do not advertise S256 keep the existing plain flow, and if the discovery document cannot be read at startup, sign-in continues without PKCE and a warning is logged. Nothing changes in the OIDC settings screens, and existing provider configurations need no changes.
- _Files: `backend/oidc_handler.py`, `tests/test_oidc_pkce.py`_
- **Dependency updates: Authlib 1.9.5 and Apprise 2.2.0 (#291, #256):** Authlib moves from 1.9.2 to 1.9.5, three upstream security releases: 1.9.3 refuses form_post responses to non-http(s) redirect URIs in the implicit and hybrid grants, 1.9.4 fixes ID-JAG user resolution for multi-tenant providers, and 1.9.5 completes the fix for CVE-2026-114615 by refusing public keys and certificates as HMAC secrets. Warracker uses Authlib as an OIDC client rather than an authorization server, so these are taken as auth-stack hygiene alongside the new PKCE support. Apprise moves from 1.13.1 to 2.2.0, a major release carrying the upstream security fix GHSA-cfp4-m43r-v9q4 and a dozen new notification services. Behavior changes in Apprise 2 that touch notifications: `notify()` returns a detailed result object instead of True/False/None, deliveries to multiple targets run in parallel by default, and retries are tracked per target. Warracker reads the result the same way it always has, sent only when every target was delivered to, and the handler now coerces the result to a plain bool, so test, custom, and expiration notifications behave identically for callers. The deprecated Apprise options removed in 2.0 were not in use.
diff --git a/Docker/.env.example b/Docker/.env.example
index 45a9ce4..629a22a 100644
--- a/Docker/.env.example
+++ b/Docker/.env.example
@@ -10,9 +10,10 @@ DB_NAME=warranty_db
DB_USER=warranty_user
DB_PASSWORD=warranty_password
-# Database admin credentials (used for migrations and setup)
-DB_ADMIN_USER=warracker_admin
-DB_ADMIN_PASSWORD=change_this_password_in_production
+# Optional: set both DB_ADMIN_USER and DB_ADMIN_PASSWORD if you want initial
+# migrations to create a separate PostgreSQL admin role (no built-in defaults).
+# DB_ADMIN_USER=warracker_admin
+# DB_ADMIN_PASSWORD=your_secure_admin_password
# PostgreSQL-specific settings (for the database container)
POSTGRES_DB=warranty_db
diff --git a/backend/config.py b/backend/config.py
index 2eb5e79..4a74b0a 100644
--- a/backend/config.py
+++ b/backend/config.py
@@ -171,16 +171,19 @@ class Config:
MAX_COOKIE_SIZE = 4093 # Slightly under 4KB limit
USE_X_SENDFILE = False # Serve files directly via Flask; nginx is not configured to handle X-Sendfile
- DB_VARS = ('DB_USER', 'DB_PASSWORD', 'DB_ADMIN_USER', 'DB_ADMIN_PASSWORD')
+ REQUIRED_DB_VARS = ('DB_USER', 'DB_PASSWORD')
+ OPTIONAL_DB_ADMIN_VARS = ('DB_ADMIN_USER', 'DB_ADMIN_PASSWORD')
+ DB_VARS = REQUIRED_DB_VARS + OPTIONAL_DB_ADMIN_VARS
@staticmethod
def _missing_db_vars(app):
"""Return required database credential variables with no value.
- DATABASE_URL can supply the application user and password, as it
- already takes precedence in the database handlers. The separate
- admin credentials remain required because migrations use them to
- manage the application role.
+ DB_USER and DB_PASSWORD are required, though DATABASE_URL can
+ supply them because it takes precedence in the database handlers.
+ DB_ADMIN_USER and DB_ADMIN_PASSWORD are optional (only used by
+ the optional 010_configure_admin_roles.sql migration) and have no
+ built-in defaults; if one is set, the other must also be set.
"""
if app.config.get('TESTING'):
return []
@@ -194,7 +197,15 @@ class Config:
if parsed.password and not values['DB_PASSWORD']:
values['DB_PASSWORD'] = unquote(parsed.password)
- return [var for var, value in values.items() if not value]
+ missing = [var for var in Config.REQUIRED_DB_VARS if not values[var]]
+ admin_user_set = bool(values['DB_ADMIN_USER'])
+ admin_password_set = bool(values['DB_ADMIN_PASSWORD'])
+ if admin_user_set != admin_password_set:
+ if not admin_user_set:
+ missing.append('DB_ADMIN_USER')
+ if not admin_password_set:
+ missing.append('DB_ADMIN_PASSWORD')
+ return missing
@staticmethod
def _validate_db_vars(app):
@@ -203,8 +214,10 @@ class Config:
raise RuntimeError(
"Missing required database environment variables: "
+ ', '.join(missing_vars)
- + ". Set DB_USER, DB_PASSWORD, DB_ADMIN_USER, and "
- "DB_ADMIN_PASSWORD in your environment or .env file."
+ + ". Set DB_USER and DB_PASSWORD (or DATABASE_URL with "
+ "credentials) in your environment or .env file. "
+ "DB_ADMIN_USER and DB_ADMIN_PASSWORD are optional, but "
+ "must be set together if used."
)
@staticmethod
diff --git a/backend/migrations/010_configure_admin_roles.sql b/backend/migrations/010_configure_admin_roles.sql
index 40e519b..0e24ccc 100644
--- a/backend/migrations/010_configure_admin_roles.sql
+++ b/backend/migrations/010_configure_admin_roles.sql
@@ -1,36 +1,46 @@
-- Migration: Configure PostgreSQL Admin Role
--- This is optional role management - will be skipped if permissions are insufficient
+-- This is optional role management - skipped when DB_ADMIN_USER and
+-- DB_ADMIN_PASSWORD are not set, or if privileges are insufficient.
-DO $$
+DO $$
+DECLARE
+ admin_user text := %(db_admin_user_name)s;
+ admin_password text := %(db_admin_password)s;
+ target_db text := %(db_name_literal)s;
BEGIN
+ IF admin_user IS NULL OR admin_user = '' OR admin_password IS NULL OR admin_password = '' THEN
+ RAISE NOTICE 'DB_ADMIN_USER/DB_ADMIN_PASSWORD not set - skipping optional admin role configuration';
+ RETURN;
+ END IF;
+
-- Try to create admin role, but continue if it fails
BEGIN
-- Check if the db_admin_user exists, if not create it
- IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = %(db_admin_user_name)s) THEN
- CREATE ROLE %(db_admin_user)s WITH LOGIN PASSWORD %(db_admin_password)s;
- RAISE NOTICE 'Successfully created admin role %(db_admin_user)s';
+ IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = admin_user) THEN
+ EXECUTE format('CREATE ROLE %%I WITH LOGIN PASSWORD %%L', admin_user, admin_password);
+ RAISE NOTICE 'Successfully created admin role %%', admin_user;
END IF;
-- Grant privileges to the admin role
- GRANT ALL PRIVILEGES ON DATABASE %(db_name)s TO %(db_admin_user)s;
- GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO %(db_admin_user)s;
- GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO %(db_admin_user)s;
- GRANT ALL PRIVILEGES ON ALL FUNCTIONS IN SCHEMA public TO %(db_admin_user)s;
+ EXECUTE format('GRANT ALL PRIVILEGES ON DATABASE %%I TO %%I', target_db, admin_user);
+ EXECUTE format('GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO %%I', admin_user);
+ EXECUTE format('GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO %%I', admin_user);
+ EXECUTE format('GRANT ALL PRIVILEGES ON ALL FUNCTIONS IN SCHEMA public TO %%I', admin_user);
-- Try to grant CREATEROLE, but continue if it fails
BEGIN
- ALTER ROLE %(db_admin_user)s WITH CREATEROLE;
- RAISE NOTICE 'Successfully granted CREATEROLE to %(db_admin_user)s';
+ EXECUTE format('ALTER ROLE %%I WITH CREATEROLE', admin_user);
+ RAISE NOTICE 'Successfully granted CREATEROLE to %%', admin_user;
EXCEPTION WHEN insufficient_privilege THEN
- RAISE NOTICE 'Insufficient privileges to grant CREATEROLE to %(db_admin_user)s - role management features may be limited';
+ RAISE NOTICE 'Insufficient privileges to grant CREATEROLE to %% - role management features may be limited', admin_user;
WHEN OTHERS THEN
- RAISE NOTICE 'Could not grant CREATEROLE to %(db_admin_user)s - role management features may be limited';
+ RAISE NOTICE 'Could not grant CREATEROLE to %% - role management features may be limited', admin_user;
END;
EXCEPTION WHEN insufficient_privilege THEN
- RAISE NOTICE 'Insufficient privileges to create admin role %(db_admin_user)s - this is optional and the application will work without it';
+ RAISE NOTICE 'Insufficient privileges to create admin role %% - this is optional and the application will work without it', admin_user;
WHEN OTHERS THEN
- RAISE NOTICE 'Could not create admin role %(db_admin_user)s - this is optional and the application will work without it';
+ RAISE NOTICE 'Could not create admin role %% - this is optional and the application will work without it', admin_user;
END;
END
$$;
@@ -42,4 +52,4 @@ GRANT ALL PRIVILEGES ON ALL FUNCTIONS IN SCHEMA public TO %(db_user)s;
-- Make db_admin_user the owner of all existing users
-- Note: This would require superuser privileges to execute
--- ALTER ROLE %(db_user)s OWNER TO %(db_admin_user)s;
+-- ALTER ROLE <db_user> OWNER TO <db_admin_user>;
diff --git a/backend/migrations/apply_migrations.py b/backend/migrations/apply_migrations.py
index 8fa8ec5..65aafba 100644
--- a/backend/migrations/apply_migrations.py
+++ b/backend/migrations/apply_migrations.py
@@ -70,17 +70,19 @@ def _validate_db_credentials():
missing.append('DB_USER')
if not DB_PASSWORD:
missing.append('DB_PASSWORD')
- if not DB_ADMIN_USER:
- missing.append('DB_ADMIN_USER')
- if not DB_ADMIN_PASSWORD:
- missing.append('DB_ADMIN_PASSWORD')
+ if bool(DB_ADMIN_USER) != bool(DB_ADMIN_PASSWORD):
+ if not DB_ADMIN_USER:
+ missing.append('DB_ADMIN_USER')
+ if not DB_ADMIN_PASSWORD:
+ missing.append('DB_ADMIN_PASSWORD')
if missing:
raise RuntimeError(
"Missing required database environment variables: "
+ ', '.join(missing)
- + ". Set all four variables in your environment or .env file; "
- "DATABASE_URL must include a username and password when it is "
- "used instead of DB_USER and DB_PASSWORD."
+ + ". Set DB_USER and DB_PASSWORD in your environment or .env file "
+ "(DATABASE_URL must include a username and password when used "
+ "instead). DB_ADMIN_USER and DB_ADMIN_PASSWORD are optional, "
+ "but must be set together if used."
)
def get_db_connection(max_attempts=5, attempt_delay=5):
@@ -175,23 +177,32 @@ def apply_migrations():
sql = f.read()
# Check if the SQL has placeholders before passing parameters
- if any(placeholder in sql for placeholder in ['%(db_name)s', '%(db_user)s', '%(db_admin_user)s', '%(db_admin_password)s']):
- cur.execute(
- sql,
- {
- # Identifiers are double-quoted so PostgreSQL
- # preserves their case (issue #187)
- "db_name": AsIs(_quote_ident(DB_NAME)),
- "db_user": AsIs(_quote_ident(DB_USER)),
- "db_admin_user": AsIs(_quote_ident(DB_ADMIN_USER)),
- # Raw names for string-literal contexts
- # (e.g. rolname comparisons)
- "db_user_name": DB_USER,
- "db_admin_user_name": DB_ADMIN_USER,
- # Password is a value: let psycopg2 escape it
- "db_admin_password": DB_ADMIN_PASSWORD,
- }
- )
+ placeholders = (
+ '%(db_name)s',
+ '%(db_name_literal)s',
+ '%(db_user)s',
+ '%(db_user_name)s',
+ '%(db_admin_user)s',
+ '%(db_admin_user_name)s',
+ '%(db_admin_password)s',
+ )
+ if any(placeholder in sql for placeholder in placeholders):
+ params = {
+ # Identifiers are double-quoted so PostgreSQL
+ # preserves their case (issue #187)
+ "db_name": AsIs(_quote_ident(DB_NAME)),
+ "db_user": AsIs(_quote_ident(DB_USER)),
+ # Raw names for string-literal contexts
+ # (e.g. rolname comparisons and format('%I', ...))
+ "db_name_literal": DB_NAME,
+ "db_user_name": DB_USER,
+ "db_admin_user_name": DB_ADMIN_USER,
+ # Password is a value: let psycopg2 escape it
+ "db_admin_password": DB_ADMIN_PASSWORD,
+ }
+ if DB_ADMIN_USER:
+ params["db_admin_user"] = AsIs(_quote_ident(DB_ADMIN_USER))
+ cur.execute(sql, params)
else:
# No placeholders, execute directly
cur.execute(sql)
diff --git a/env.example b/env.example
index 2f8c1eb..a85a938 100644
--- a/env.example
+++ b/env.example
@@ -2,12 +2,14 @@
# Copy this file to .env and modify the values as needed
# Database Configuration
-# Set all four variables explicitly. There are no built-in defaults:
-# startup fails if any required database credential is missing.
+# Set DB_USER and DB_PASSWORD explicitly (or supply credentials via DATABASE_URL).
+# There are no built-in defaults: startup fails if required credentials are missing.
DB_USER=warranty_user
DB_PASSWORD=your_secure_database_password
-DB_ADMIN_USER=warracker_admin
-DB_ADMIN_PASSWORD=your_secure_admin_password
+# Optional: set both DB_ADMIN_USER and DB_ADMIN_PASSWORD if you want initial
+# migrations to create a separate PostgreSQL admin role (no built-in defaults).
+# DB_ADMIN_USER=warracker_admin
+# DB_ADMIN_PASSWORD=your_secure_admin_password
# DB_HOST=warrackerdb
# DB_NAME=warranty_db
# DB_PORT=5432
diff --git a/tests/test_db_credentials_required.py b/tests/test_db_credentials_required.py
index 98b95ee..955da5a 100644
--- a/tests/test_db_credentials_required.py
+++ b/tests/test_db_credentials_required.py
@@ -1,16 +1,20 @@
"""Required database credentials for 1.0.7 (#221).
The built-in defaults for DB_USER, DB_PASSWORD, DB_ADMIN_USER, and
-DB_ADMIN_PASSWORD are gone. Startup and the standalone database scripts
-must fail with a clear message naming what is missing, instead of
-silently falling back to known credentials.
+DB_ADMIN_PASSWORD are gone. DB_USER and DB_PASSWORD (or DATABASE_URL
+with credentials) remain strictly required. DB_ADMIN_USER and
+DB_ADMIN_PASSWORD are optional with no built-in defaults: omitting both
+skips the optional admin role in 010_configure_admin_roles.sql, while
+setting only one fails closed naming the missing counterpart.
"""
import importlib.util
import json
import os
import subprocess
import sys
+import uuid
+import psycopg2
import pytest
from flask import Flask
@@ -28,25 +32,42 @@ def _app_with_db_values(**values):
return app
-def test_missing_all_db_vars_are_named(monkeypatch):
+def test_missing_required_db_vars_are_named(monkeypatch):
monkeypatch.delenv("DATABASE_URL", raising=False)
app = _app_with_db_values()
- assert Config._missing_db_vars(app) == list(DB_VARS)
+ assert Config._missing_db_vars(app) == ["DB_USER", "DB_PASSWORD"]
with pytest.raises(RuntimeError) as excinfo:
Config.init_app(app)
- for var in DB_VARS:
- assert var in str(excinfo.value)
+ assert "DB_USER" in str(excinfo.value)
+ assert "DB_PASSWORD" in str(excinfo.value)
-def test_missing_only_admin_vars_are_named(monkeypatch):
+def test_optional_admin_vars_may_both_be_unset(monkeypatch):
monkeypatch.delenv("DATABASE_URL", raising=False)
app = _app_with_db_values(DB_USER="alice", DB_PASSWORD="secret")
- assert Config._missing_db_vars(app) == ["DB_ADMIN_USER", "DB_ADMIN_PASSWORD"]
+ assert Config._missing_db_vars(app) == []
+ Config.init_app(app)
+ assert app.config["MAX_CONTENT_LENGTH"] > 0
+
+
+def test_partial_admin_vars_are_rejected(monkeypatch):
+ monkeypatch.delenv("DATABASE_URL", raising=False)
+
+ app_user_only = _app_with_db_values(
+ DB_USER="alice", DB_PASSWORD="secret", DB_ADMIN_USER="admin")
+ assert Config._missing_db_vars(app_user_only) == ["DB_ADMIN_PASSWORD"]
+ with pytest.raises(RuntimeError, match="DB_ADMIN_PASSWORD"):
+ Config.init_app(app_user_only)
+
+ app_pass_only = _app_with_db_values(
+ DB_USER="alice", DB_PASSWORD="secret", DB_ADMIN_PASSWORD="admin-secret")
+ assert Config._missing_db_vars(app_pass_only) == ["DB_ADMIN_USER"]
+ with pytest.raises(RuntimeError, match="DB_ADMIN_USER"):
+ Config.init_app(app_pass_only)
def test_database_url_can_supply_app_credentials(monkeypatch):
- app = _app_with_db_values(
- DB_ADMIN_USER="admin", DB_ADMIN_PASSWORD="admin-secret")
+ app = _app_with_db_values()
monkeypatch.setenv(
"DATABASE_URL", "postgresql://alice:secret@db:5432/warranty_db")
assert Config._missing_db_vars(app) == []
@@ -55,6 +76,11 @@ def test_database_url_can_supply_app_credentials(monkeypatch):
"DATABASE_URL", "postgresql://alice@db:5432/warranty_db")
assert Config._missing_db_vars(app) == ["DB_PASSWORD"]
+ app_partial_admin = _app_with_db_values(DB_ADMIN_USER="admin")
+ monkeypatch.setenv(
+ "DATABASE_URL", "postgresql://alice:secret@db:5432/warranty_db")
+ assert Config._missing_db_vars(app_partial_admin) == ["DB_ADMIN_PASSWORD"]
+
def test_testing_config_skips_db_validation(monkeypatch):
monkeypatch.delenv("DATABASE_URL", raising=False)
@@ -123,20 +149,173 @@ def test_fix_permissions_rejects_missing_app_credentials(monkeypatch):
fix_permissions.create_db_connection(max_retries=1, retry_delay=0)
-def test_apply_migrations_rejects_missing_admin_credentials():
+def test_apply_migrations_admin_credential_rules():
spec = importlib.util.spec_from_file_location(
"apply_migrations_under_test",
os.path.join(REPO_ROOT, "backend", "migrations", "apply_migrations.py"))
migrations = importlib.util.module_from_spec(spec)
spec.loader.exec_module(migrations)
+
+ # Omitting both optional admin variables is allowed.
migrations.DB_USER = "alice"
migrations.DB_PASSWORD = "secret"
migrations.DB_ADMIN_USER = None
migrations.DB_ADMIN_PASSWORD = None
+ migrations._validate_db_credentials()
+
+ # Setting only DB_ADMIN_USER fails closed naming DB_ADMIN_PASSWORD.
+ migrations.DB_ADMIN_USER = "admin"
+ migrations.DB_ADMIN_PASSWORD = None
+ with pytest.raises(RuntimeError, match="DB_ADMIN_PASSWORD"):
+ migrations._validate_db_credentials()
+
+ # Setting only DB_ADMIN_PASSWORD fails closed naming DB_ADMIN_USER.
+ migrations.DB_ADMIN_USER = None
+ migrations.DB_ADMIN_PASSWORD = "admin-secret"
+ with pytest.raises(RuntimeError, match="DB_ADMIN_USER"):
+ migrations._validate_db_credentials()
+
+ # Missing app credentials still fail closed.
+ migrations.DB_USER = None
+ migrations.DB_PASSWORD = None
+ migrations.DB_ADMIN_USER = None
+ migrations.DB_ADMIN_PASSWORD = None
with pytest.raises(RuntimeError) as excinfo:
migrations._validate_db_credentials()
- assert "DB_ADMIN_USER" in str(excinfo.value)
- assert "DB_ADMIN_PASSWORD" in str(excinfo.value)
+ assert "DB_USER" in str(excinfo.value)
+ assert "DB_PASSWORD" in str(excinfo.value)
+
+
+def _connect_pg(dbname):
+ return psycopg2.connect(
+ host=os.environ["DB_HOST"],
+ port=os.environ["DB_PORT"],
+ dbname=dbname,
+ user=os.environ["DB_USER"],
+ password=os.environ["DB_PASSWORD"],
+ )
+
+
+def _create_scratch_db():
+ dbname = f"warranty_creds_{uuid.uuid4().hex[:8]}"
+ conn = _connect_pg("postgres")
+ conn.autocommit = True
+ try:
+ with conn.cursor() as cur:
+ cur.execute(
+ f'CREATE DATABASE "{dbname}" OWNER "{os.environ["DB_USER"]}"'
+ )
+ finally:
+ conn.close()
+ return dbname
+
+
+def _drop_scratch_db(dbname):
+ conn = _connect_pg("postgres")
+ conn.autocommit = True
+ try:
+ with conn.cursor() as cur:
+ cur.execute(
+ "SELECT pg_terminate_backend(pid) FROM pg_stat_activity "
+ "WHERE datname = %s",
+ (dbname,),
+ )
+ cur.execute(f'DROP DATABASE IF EXISTS "{dbname}"')
+ finally:
+ conn.close()
+
+
+def test_apply_migrations_fresh_db_without_admin_credentials():
+ """Fresh database migrates cleanly with only DB_USER and DB_PASSWORD."""
+ dbname = _create_scratch_db()
+ try:
+ conn = _connect_pg(dbname)
+ try:
+ with conn.cursor() as cur:
+ cur.execute("SELECT rolname FROM pg_roles")
+ roles_before = {row[0] for row in cur.fetchall()}
+ finally:
+ conn.close()
+
+ env = {
+ k: v for k, v in os.environ.items()
+ if k not in ("DB_ADMIN_USER", "DB_ADMIN_PASSWORD", "DATABASE_URL")
+ }
+ env["DB_NAME"] = dbname
+ script = os.path.join(
+ REPO_ROOT, "backend", "migrations", "apply_migrations.py"
+ )
+ result = subprocess.run(
+ [sys.executable, script],
+ env=env, capture_output=True, text=True, timeout=600,
+ )
+ assert result.returncode == 0, result.stdout[-3000:] + result.stderr[-3000:]
+
+ conn = _connect_pg(dbname)
+ try:
+ with conn.cursor() as cur:
+ cur.execute("SELECT filename FROM migrations")
+ applied = {row[0] for row in cur.fetchall()}
+ assert "010_configure_admin_roles.sql" in applied
+ cur.execute("SELECT to_regclass('warranties')")
+ assert cur.fetchone()[0] is not None
+ cur.execute("SELECT rolname FROM pg_roles")
+ roles_after = {row[0] for row in cur.fetchall()}
+ assert roles_after == roles_before
+ finally:
+ conn.close()
+ finally:
+ _drop_scratch_db(dbname)
+
+
+def test_apply_migrations_fresh_db_with_explicit_admin_credentials():
+ """Explicit DB_ADMIN_USER + DB_ADMIN_PASSWORD still apply cleanly (including % in password)."""
+ dbname = _create_scratch_db()
+ admin_role = f"WarrackerAdmin_{uuid.uuid4().hex[:6]}"
+ try:
+ env = {k: v for k, v in os.environ.items() if k != "DATABASE_URL"}
+ env["DB_NAME"] = dbname
+ env["DB_ADMIN_USER"] = admin_role
+ env["DB_ADMIN_PASSWORD"] = "Strong%AdminPass!123"
+ script = os.path.join(
+ REPO_ROOT, "backend", "migrations", "apply_migrations.py"
+ )
+ result = subprocess.run(
+ [sys.executable, script],
+ env=env, capture_output=True, text=True, timeout=600,
+ )
+ assert result.returncode == 0, result.stdout[-3000:] + result.stderr[-3000:]
+
+ conn = _connect_pg(dbname)
+ try:
+ with conn.cursor() as cur:
+ cur.execute("SELECT filename FROM migrations")
+ applied = {row[0] for row in cur.fetchall()}
+ assert "010_configure_admin_roles.sql" in applied
+ cur.execute(
+ "SELECT rolcreaterole, rolsuper FROM pg_roles WHERE rolname = %s",
+ (os.environ["DB_USER"],),
+ )
+ can_create_role = any(cur.fetchone() or (False, False))
+ if can_create_role:
+ cur.execute(
+ "SELECT 1 FROM pg_roles WHERE rolname = %s",
+ (admin_role,),
+ )
+ assert cur.fetchone() is not None
+ finally:
+ conn.close()
+ finally:
+ _drop_scratch_db(dbname)
+ conn = _connect_pg("postgres")
+ conn.autocommit = True
+ try:
+ with conn.cursor() as cur:
+ cur.execute(f'DROP ROLE IF EXISTS "{admin_role}"')
+ except psycopg2.Error:
+ pass
+ finally:
+ conn.close()
def test_no_credential_fallbacks_remain_in_runtime_sources():
@@ -161,3 +340,5 @@ def test_no_credential_fallbacks_remain_in_runtime_sources():
unraid_template = open(os.path.join(REPO_ROOT, "unraid", "warracker.xml")).read()
assert "default_admin_password" not in unraid_template
+ assert 'Target="DB_ADMIN_USER" Default=""' in unraid_template
+ assert 'Target="DB_ADMIN_PASSWORD" Default=""' in unraid_template
diff --git a/unraid/warracker.xml b/unraid/warracker.xml
index 0382f05..ee5b6a1 100644
--- a/unraid/warracker.xml
+++ b/unraid/warracker.xml
@@ -50,13 +50,13 @@
Description="PostgreSQL password." Type="Variable"
Display="always" Required="true" Mask="true"></Config>
- <Config Name="DB_ADMIN_USER" Target="DB_ADMIN_USER" Default="warracker_admin" Mode=""
- Description="PostgreSQL admin username, used for database migrations. Required: Warracker has no built-in default. Pre-filled with the example value; change it if your PostgreSQL admin user differs." Type="Variable"
- Display="always" Required="true" Mask="false">warracker_admin</Config>
+ <Config Name="DB_ADMIN_USER" Target="DB_ADMIN_USER" Default="" Mode=""
+ Description="Optional PostgreSQL admin username created by initial migrations. Leave both DB_ADMIN_USER and DB_ADMIN_PASSWORD blank unless you want Warracker to create a separate PostgreSQL admin role (no built-in default)." Type="Variable"
+ Display="advanced" Required="false" Mask="false"></Config>
<Config Name="DB_ADMIN_PASSWORD" Target="DB_ADMIN_PASSWORD" Default="" Mode=""
- Description="PostgreSQL admin password, used for database migrations. Required: Warracker has no built-in default. Set it to your PostgreSQL admin password." Type="Variable"
- Display="always" Required="true" Mask="true"></Config>
+ Description="Optional PostgreSQL admin password paired with DB_ADMIN_USER. Leave blank if DB_ADMIN_USER is blank; required if DB_ADMIN_USER is set (no built-in default)." Type="Variable"
+ Display="advanced" Required="false" Mask="true"></Config>
<Config Name="SECRET_KEY" Target="SECRET_KEY" Default="" Mode=""
Description="Secret key for Flask sessions and JWT. Generate a random string (e.g. openssl rand -hex 32)." Type="Variable"