Skip to content

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

Honor DATABASE_URL in entrypoint/fix_permissions, drop compose DB_ADMIN fallback, document 1.0.7 env vars

sassanixbcc11c82915c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8ac4eb4..d72f435 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 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`_
+- **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, now also honored by the Docker entrypoint readiness probe and `fix_permissions.py`) 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. Both shipped Compose files, both env examples, and the Unraid template leave both admin variables commented out/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`, `docker-compose.yml`, `Docker/docker-compose.yml`, `env.example`, `Docker/.env.example`, `unraid/warracker.xml`, `tests/conftest.py`, `.github/workflows/tests.yml`, `tests/test_db_credentials_required.py`, `tests/test_compose_cfg05.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.
@@ -31,7 +31,7 @@
- **Security hardening, Paperless sharing:** an upload in flight can no longer be claimed by another user linking its pending id, because the uploader now reclaims any ownership claim recorded after the upload started, while claims predating the upload are untouched. A duplicate upload no longer reveals another user's document id, and searching and linking by title now answers identically whether the document is missing or belongs to someone else. The Paperless tag list is now scoped to the documents the requesting user can see, instead of returning every tag on the instance, and the search page size forwarded to Paperless is capped at 100.
- _Files: `backend/file_routes.py`, `backend/paperless_access.py`, `tests/test_paperless_lows.py`, `tests/test_paperless_security.py`, `tests/mock_paperless.py`_
- **Security hardening, photo by URL:** the address guard now also rejects NAT64 translation addresses and other translation wrappers embedding a private IPv4, which previously passed the public-address check. The fetch now has a total deadline (60 seconds by default, tunable with `PHOTO_FETCH_TIMEOUT_SECONDS`) covering redirects and the body read, so a server dripping data slowly can no longer hold a fetch open indefinitely.
- - _Files: `backend/warranties_routes.py`, `tests/test_photo_url.py`_
+ - _Files: `backend/config.py`, `backend/warranties_routes.py`, `tests/test_photo_url.py`_
- **Security hardening, rendering:** tag names and colors are now escaped everywhere they render, in the tag picker, the selected-tag chips, Manage Tags, and the legacy tag renders, and the shared escaping helper now escapes quotes in every definition, so a quote in a tag name can no longer break out of an input value. The Settings Paperless debug, test-connection, and test-upload displays now escape the server-controlled strings they show, so a hostile Paperless reason phrase renders as text instead of markup.
- _Files: `frontend/js/components/tagManager.js`, `frontend/script.js`, `frontend/settings-new.js`, `tests/test_xss_regressions.py`_
- **Security hardening, Apprise audit trail:** Apprise test notifications and custom notifications now write an entry to the admin audit log, including whether per-request URLs were used and whether the send succeeded. The entries record only the URL schemes and the count, never hosts, paths, credentials, or notification content, since Apprise URLs embed secrets.
diff --git a/Docker/.env.example b/Docker/.env.example
index 629a22a..727e33f 100644
--- a/Docker/.env.example
+++ b/Docker/.env.example
@@ -29,6 +29,15 @@ POSTGRES_PASSWORD=warranty_password
# random key on first start and persists it to a file.
SECRET_KEY=
+# Optional: custom path for persisting an auto-generated SECRET_KEY (defaults to $UPLOAD_FOLDER/.secret_key)
+# SECRET_KEY_FILE=/data/uploads/.secret_key
+
+# Optional: set to true only if behind a reverse proxy on a public IP (local/private proxies are trusted automatically)
+# TRUST_PROXY_HEADERS=false
+
+# Optional: comma-separated origins allowed to send cross-origin requests with credentials
+# CORS_ALLOWED_ORIGINS=
+
# JWT token expiration time (in hours)
JWT_EXPIRATION_HOURS=24
@@ -65,6 +74,9 @@ MAX_UPLOAD_MB=32
# Nginx maximum body size (should match or exceed MAX_UPLOAD_MB)
NGINX_MAX_BODY_SIZE_VALUE=32M
+# Optional: total timeout (seconds) when fetching a product photo from a URL (default: 60)
+# PHOTO_FETCH_TIMEOUT_SECONDS=60
+
### **Performance & Memory Configuration**
@@ -75,6 +87,11 @@ NGINX_MAX_BODY_SIZE_VALUE=32M
# - performance: 4 workers, ~150-200MB RAM usage (for high-traffic deployments)
WARRACKER_MEMORY_MODE=optimized
+# Optional: per-worker PostgreSQL connection pool sizing and wait timeout
+# DB_POOL_MIN=1
+# DB_POOL_MAX=4
+# DB_POOL_WAIT_SECONDS=30
+
### **OIDC/SSO Configuration (Optional)**
@@ -145,7 +162,6 @@ OIDC_SCOPE=openid email profile
```bash
SECRET_KEY=super_long_random_string_generated_securely
DB_PASSWORD=strong_database_password_123
-DB_ADMIN_PASSWORD=different_strong_admin_password_456
FRONTEND_URL=https://warracker.yourdomain.com
APP_BASE_URL=https://warracker.yourdomain.com
SMTP_HOST=smtp.yourdomain.com
@@ -159,7 +175,7 @@ WARRACKER_MEMORY_MODE=performance
1. **Copy this configuration** into a file named `.env` in your Docker folder
2. **Customize the values** according to your specific deployment needs
-3. **Generate strong passwords** for production use, especially for `SECRET_KEY`, `DB_PASSWORD`, and `DB_ADMIN_PASSWORD`
+3. **Generate strong passwords** for production use, especially for `SECRET_KEY` and `DB_PASSWORD` (and `DB_ADMIN_PASSWORD` if using the optional admin role)
4. **Set your domain URLs** correctly for `FRONTEND_URL` and `APP_BASE_URL` if deploying publicly
5. **Configure SMTP** if you want email functionality for password resets and notifications
6. **Set up OIDC/SSO** if you want single sign-on capabilities
\ No newline at end of file
diff --git a/Docker/docker-compose.yml b/Docker/docker-compose.yml
index 7d2d5c6..dab110e 100644
--- a/Docker/docker-compose.yml
+++ b/Docker/docker-compose.yml
@@ -11,8 +11,9 @@ services:
- DB_NAME=warranty_db
- DB_USER=warranty_user
- DB_PASSWORD=${DB_PASSWORD:-warranty_password}
- - DB_ADMIN_USER=warracker_admin
- - DB_ADMIN_PASSWORD=${DB_ADMIN_PASSWORD:-change_this_password_in_production}
+ # Optional: set both if you want initial migrations to create a separate PostgreSQL admin role
+ # - DB_ADMIN_USER=warracker_admin
+ # - DB_ADMIN_PASSWORD=${DB_ADMIN_PASSWORD}
- SMTP_HOST=smtp.email.com
- SMTP_PORT=465
diff --git a/Docker/entrypoint.sh b/Docker/entrypoint.sh
index 7f6901f..55747b7 100644
--- a/Docker/entrypoint.sh
+++ b/Docker/entrypoint.sh
@@ -20,10 +20,27 @@ echo "=== Warracker ${APP_VERSION} ==="
# Configuration summary: the values support questions ask for first
# when a user pastes their startup log. Passwords are never printed.
-DB_DISPLAY_HOST="${DB_HOST:-localhost}"
-DB_DISPLAY_PORT="${DB_PORT:-5432}"
-DB_DISPLAY_NAME="${DB_NAME:-warranty_db}"
-DB_DISPLAY_USER="${DB_USER:-not set}"
+# When DATABASE_URL is set, derive host/port/name/user from it so both
+# the summary and the TCP readiness probe match the backend.
+if [ -n "${DATABASE_URL:-}" ]; then
+ IFS=$'\t' read -r DB_DISPLAY_HOST DB_DISPLAY_PORT DB_DISPLAY_NAME DB_DISPLAY_USER < <(
+ python -c "
+import os
+from urllib.parse import urlparse, unquote
+p = urlparse(os.environ['DATABASE_URL'])
+host = p.hostname or 'localhost'
+port = str(p.port) if p.port else '5432'
+name = (p.path or '').lstrip('/') or 'warranty_db'
+user = unquote(p.username) if p.username else 'not set'
+print(f'{host}\t{port}\t{name}\t{user}')
+"
+ )
+else
+ DB_DISPLAY_HOST="${DB_HOST:-localhost}"
+ DB_DISPLAY_PORT="${DB_PORT:-5432}"
+ DB_DISPLAY_NAME="${DB_NAME:-warranty_db}"
+ DB_DISPLAY_USER="${DB_USER:-not set}"
+fi
log "Database: ${DB_DISPLAY_HOST}:${DB_DISPLAY_PORT}, database ${DB_DISPLAY_NAME}, user ${DB_DISPLAY_USER}"
if [ "${DISABLE_NGINX:-false}" = "true" ]; then
log "Web: nginx disabled, gunicorn serves directly on port 5000"
@@ -43,10 +60,10 @@ fi
# replaces pg_isready, so the image no longer needs postgresql-client.
log "Waiting for database connection to ${DB_DISPLAY_HOST}:${DB_DISPLAY_PORT}..."
for i in {1..30}; do
- if python -c "
+ if DB_WAIT_HOST="${DB_DISPLAY_HOST}" DB_WAIT_PORT="${DB_DISPLAY_PORT}" python -c "
import os, socket, sys
try:
- with socket.create_connection((os.environ.get('DB_HOST', 'localhost'), int(os.environ.get('DB_PORT', '5432'))), timeout=2):
+ with socket.create_connection((os.environ['DB_WAIT_HOST'], int(os.environ['DB_WAIT_PORT'])), timeout=2):
sys.exit(0)
except OSError:
sys.exit(1)
diff --git a/backend/fix_permissions.py b/backend/fix_permissions.py
index 276d990..dd7cbc1 100644
--- a/backend/fix_permissions.py
+++ b/backend/fix_permissions.py
@@ -8,25 +8,59 @@ import stat
import pwd
import grp
+from urllib.parse import parse_qsl, unquote, urlparse
+
from psycopg2.extensions import AsIs
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
+
+def _quote_ident(name):
+ """Quote a PostgreSQL identifier, preserving case (issue #187)."""
+ return '"' + str(name).replace('"', '""') + '"'
+
+
+def _db_parts():
+ url = os.environ.get('DATABASE_URL')
+ if url:
+ p = urlparse(url)
+ parts = {
+ 'host': p.hostname or 'localhost',
+ 'port': str(p.port) if p.port else '5432',
+ 'name': (p.path or '').lstrip('/') or 'warranty_db',
+ 'user': unquote(p.username) if p.username else None,
+ 'password': unquote(p.password) if p.password else None,
+ }
+ options = dict(parse_qsl(p.query, keep_blank_values=True))
+ if options:
+ parts['options'] = options
+ return parts
+ return {
+ 'host': os.environ.get('DB_HOST', 'warrackerdb'),
+ 'port': os.environ.get('DB_PORT', '5432'),
+ 'name': os.environ.get('DB_NAME', 'warranty_db'),
+ 'user': os.environ.get('DB_USER'),
+ 'password': os.environ.get('DB_PASSWORD'),
+ }
+
+
# PostgreSQL connection details
-DB_HOST = os.environ.get('DB_HOST', 'warrackerdb')
-DB_PORT = os.environ.get('DB_PORT', '5432')
-DB_NAME = os.environ.get('DB_NAME', 'warranty_db')
-DB_USER = os.environ.get('DB_USER')
-DB_PASSWORD = os.environ.get('DB_PASSWORD')
+_DB = _db_parts()
+DB_HOST = _DB['host']
+DB_PORT = _DB['port']
+DB_NAME = _DB['name']
+DB_USER = _DB['user']
+DB_PASSWORD = _DB['password']
def create_db_connection(max_retries=5, retry_delay=5):
"""Create a database connection with retry logic"""
if not DB_USER or not DB_PASSWORD:
raise RuntimeError(
"Missing required database environment variables: "
- "DB_USER and DB_PASSWORD must be set."
+ "DB_USER and DB_PASSWORD must be set (or DATABASE_URL must "
+ "include a username and password)."
)
attempt = 0
last_exception = None
@@ -39,7 +73,8 @@ def create_db_connection(max_retries=5, retry_delay=5):
port=DB_PORT,
database=DB_NAME,
user=DB_USER,
- password=DB_PASSWORD
+ password=DB_PASSWORD,
+ **_DB.get('options', {}),
)
logger.info("Database connection successful")
return conn
@@ -126,8 +161,8 @@ def fix_database_permissions():
cursor.execute(
sql_script,
{
- "db_name": AsIs(DB_NAME),
- "db_user": AsIs(DB_USER),
+ "db_name": AsIs(_quote_ident(DB_NAME)),
+ "db_user": AsIs(_quote_ident(DB_USER)),
}
)
diff --git a/docker-compose.yml b/docker-compose.yml
index afcd8a3..5e53b0f 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -14,8 +14,9 @@ services:
- DB_NAME=warranty_test
- DB_USER=warranty_user
- DB_PASSWORD=${DB_PASSWORD:-warranty_password}
- - DB_ADMIN_USER=warracker_admin
- - DB_ADMIN_PASSWORD=${DB_ADMIN_PASSWORD:-change_this_password_in_production}
+ # Optional: set both if you want initial migrations to create a separate PostgreSQL admin role
+ # - DB_ADMIN_USER=warracker_admin
+ # - DB_ADMIN_PASSWORD=${DB_ADMIN_PASSWORD}
- SMTP_HOST=${SMTP_HOST:-localhost}
- SMTP_PORT=${SMTP_PORT:-1025}
- SMTP_USERNAME=${SMTP_USERNAME:[email protected]}
diff --git a/env.example b/env.example
index a85a938..2ef3e56 100644
--- a/env.example
+++ b/env.example
@@ -16,6 +16,12 @@ DB_PASSWORD=your_secure_database_password
# Application Security
SECRET_KEY=your_very_secure_flask_secret_key_change_this_in_production
+# Optional: custom path for persisting an auto-generated SECRET_KEY (defaults to $UPLOAD_FOLDER/.secret_key)
+# SECRET_KEY_FILE=/data/uploads/.secret_key
+# Optional: set to true only if behind a reverse proxy on a public IP (local/private proxies are trusted automatically)
+# TRUST_PROXY_HEADERS=false
+# Optional: comma-separated origins allowed to send cross-origin requests with credentials
+# CORS_ALLOWED_ORIGINS=
# Email Configuration (for password resets and notifications)
SMTP_HOST=smtp.gmail.com
@@ -42,6 +48,12 @@ FLASK_ENV=production # Forces OIDC to route to and from https://your-warracker-d
WARRACKER_MEMORY_MODE=optimized
MAX_UPLOAD_MB=16
NGINX_MAX_BODY_SIZE_VALUE=16M
+# Optional: total timeout (seconds) when fetching a product photo from a URL (default: 60)
+# PHOTO_FETCH_TIMEOUT_SECONDS=60
+# Optional: per-worker PostgreSQL connection pool sizing and wait timeout
+# DB_POOL_MIN=1
+# DB_POOL_MAX=4
+# DB_POOL_WAIT_SECONDS=30
# =====================
# APPRISE NOTIFICATIONS
diff --git a/tests/test_compose_cfg05.py b/tests/test_compose_cfg05.py
index 6951a02..a19be62 100644
--- a/tests/test_compose_cfg05.py
+++ b/tests/test_compose_cfg05.py
@@ -43,3 +43,18 @@ def test_nginx_suppresses_version_banner():
encoding="utf-8") as fh:
src = fh.read()
assert "server_tokens off;" in src
+
+
+def test_compose_files_do_not_default_db_admin_password():
+ for rel_path in ("docker-compose.yml", "Docker/docker-compose.yml"):
+ with open(os.path.join(REPO_ROOT, rel_path),
+ encoding="utf-8") as fh:
+ src = fh.read()
+ assert "change_this_password_in_production" not in src, rel_path
+ active_lines = [
+ line for line in src.splitlines()
+ if not line.lstrip().startswith("#")
+ ]
+ active_src = "\n".join(active_lines)
+ assert "DB_ADMIN_USER=" not in active_src, rel_path
+ assert "DB_ADMIN_PASSWORD=" not in active_src, rel_path
diff --git a/tests/test_db_credentials_required.py b/tests/test_db_credentials_required.py
index 955da5a..2e33c29 100644
--- a/tests/test_db_credentials_required.py
+++ b/tests/test_db_credentials_required.py
@@ -318,6 +318,79 @@ def test_apply_migrations_fresh_db_with_explicit_admin_credentials():
conn.close()
+def test_migrations_and_fix_permissions_work_with_database_url_only(tmp_path):
+ """DATABASE_URL alone (without DB_HOST/PORT/NAME/USER/PASSWORD/DB_ADMIN_*) works end to end."""
+ from urllib.parse import quote
+
+ dbname = _create_scratch_db()
+ try:
+ user = quote(os.environ["DB_USER"], safe="")
+ pw = quote(os.environ["DB_PASSWORD"], safe="")
+ host = os.environ["DB_HOST"]
+ port = os.environ["DB_PORT"]
+ database_url = f"postgresql://{user}:{pw}@{host}:{port}/{dbname}"
+
+ stripped = {
+ "DB_HOST", "DB_PORT", "DB_NAME", "DB_USER", "DB_PASSWORD",
+ "DB_ADMIN_USER", "DB_ADMIN_PASSWORD", "DATABASE_URL",
+ }
+ env = {k: v for k, v in os.environ.items() if k not in stripped}
+ env["DATABASE_URL"] = database_url
+ env["UPLOAD_FOLDER"] = str(tmp_path / "uploads")
+
+ migrations_script = os.path.join(
+ REPO_ROOT, "backend", "migrations", "apply_migrations.py"
+ )
+ r_mig = subprocess.run(
+ [sys.executable, migrations_script],
+ env=env, capture_output=True, text=True, timeout=600,
+ )
+ assert r_mig.returncode == 0, r_mig.stdout[-3000:] + r_mig.stderr[-3000:]
+
+ fix_script = os.path.join(REPO_ROOT, "backend", "fix_permissions.py")
+ r_fix = subprocess.run(
+ [sys.executable, fix_script],
+ env=env, capture_output=True, text=True, timeout=120,
+ )
+ assert r_fix.returncode == 0, r_fix.stdout[-3000:] + r_fix.stderr[-3000:]
+ finally:
+ _drop_scratch_db(dbname)
+
+
+def test_entrypoint_honors_database_url_without_printing_password():
+ entrypoint = os.path.join(REPO_ROOT, "Docker", "entrypoint.sh")
+ syntax = subprocess.run(
+ ["bash", "-n", entrypoint], capture_output=True, text=True,
+ )
+ assert syntax.returncode == 0, syntax.stderr
+
+ src = open(entrypoint, encoding="utf-8").read()
+ assert 'if [ -n "${DATABASE_URL:-}" ]; then' in src
+ assert 'DB_WAIT_HOST="${DB_DISPLAY_HOST}" DB_WAIT_PORT="${DB_DISPLAY_PORT}"' in src
+
+ # Extract and execute only the DATABASE_URL parsing block with python3/python.
+ start = src.index('if [ -n "${DATABASE_URL:-}" ]; then')
+ end = src.index('log "Database:', start)
+ snippet = src[start:end].replace("python -c", f"{sys.executable} -c")
+ probe = (
+ snippet
+ + '\nprintf "%s|%s|%s|%s\\n" '
+ '"$DB_DISPLAY_HOST" "$DB_DISPLAY_PORT" "$DB_DISPLAY_NAME" "$DB_DISPLAY_USER"\n'
+ )
+ env = dict(os.environ)
+ env["DATABASE_URL"] = (
+ "postgresql://dbuser:SuperSecretPass%[email protected]:5433/warracker_prod?sslmode=require"
+ )
+ r = subprocess.run(
+ ["bash", "-euo", "pipefail", "-c", probe],
+ env=env, capture_output=True, text=True, timeout=30,
+ )
+ assert r.returncode == 0, r.stderr
+ assert r.stdout.strip() == "pg.internal|5433|warracker_prod|dbuser"
+ assert "SuperSecretPass" not in r.stdout
+ assert "SuperSecretPass" not in r.stderr
+
+
def test_no_credential_fallbacks_remain_in_runtime_sources():
runtime_files = [
"backend/config.py",