🛡️ Warracker is an open source, self-hostable warranty tracker to monitor expirations, store receipts, files. You own the data, your rules!
Security: serialize first-user provisioning with an advisory lock (AUTH-07)
Omega (QA)8acfc7eba64d
diff --git a/backend/auth_routes.py b/backend/auth_routes.pyindex 91628f1..26c6c0c 100644--- a/backend/auth_routes.py+++ b/backend/auth_routes.py@@ -15,7 +15,7 @@ from psycopg2.extras import Json# Use relative imports for project modulestry:from . import db_handler, notifications- from .auth_utils import generate_token, token_required, is_valid_email, is_valid_password, is_password_too_long+ from .auth_utils import generate_token, token_required, is_valid_email, is_valid_password, is_password_too_long, acquire_first_user_lockfrom .localization import SUPPORTED_LANGUAGESfrom .rate_limit import (login_limited, record_login_failure, clear_login_failures,@@ -23,7 +23,7 @@ try:except ImportError:# Fallback for development environmentimport db_handler, notifications- from auth_utils import generate_token, token_required, is_valid_email, is_valid_password, is_password_too_long+ from auth_utils import generate_token, token_required, is_valid_email, is_valid_password, is_password_too_long, acquire_first_user_lockfrom localization import SUPPORTED_LANGUAGESfrom rate_limit import (login_limited, record_login_failure, clear_login_failures,@@ -141,6 +141,14 @@ def register():password_hash = bcrypt.generate_password_hash(password).decode('utf-8')with conn.cursor() as cur:+ # AUTH-07: serialize on the first-user lock before the+ # duplicate check and the count re-read. Two concurrent+ # first registrations used to both see zero users and both+ # become owners; the second one now waits, then sees one+ # user and registers as a plain user. The bcrypt hash above+ # already ran, so the lock is never held during hashing.+ acquire_first_user_lock(cur)+# Check if username or email already existscur.execute('SELECT id FROM users WHERE username = %s OR email = %s', (username, email))existing_user = cur.fetchone()diff --git a/backend/auth_utils.py b/backend/auth_utils.pyindex 41a3411..7767f21 100644--- a/backend/auth_utils.py+++ b/backend/auth_utils.py@@ -13,6 +13,24 @@ try:except ImportError:import db_handler+# AUTH-07: one advisory lock key serializing first-user provisioning.+# Two concurrent first registrations (local or OIDC) both saw zero users+# and both became owners. Taking this lock before the user-count check+# makes the check-and-insert atomic across workers and processes.+FIRST_USER_LOCK_KEY = 20261118+++def acquire_first_user_lock(cur):+ """Take the transaction-scoped advisory lock for first-user checks.++ pg_advisory_xact_lock blocks until held, then releases at commit or+ rollback, so a connection returned to the pool can never hold it.+ Call it inside the registration transaction, before re-reading the+ user count and inserting.+ """+ cur.execute("SELECT pg_advisory_xact_lock(%s)", (FIRST_USER_LOCK_KEY,))++def generate_token(user_id):"""Generate a JWT token for the user.diff --git a/backend/oidc_handler.py b/backend/oidc_handler.pyindex 1bddb41..9ca3b68 100644--- a/backend/oidc_handler.py+++ b/backend/oidc_handler.py@@ -11,10 +11,12 @@ try:# Try relative imports (when modules are in same directory)from .extensions import oauthfrom .db_handler import get_db_connection, release_db_connection+ from .auth_utils import acquire_first_user_lockexcept ImportError:# Fallback to direct importsfrom extensions import oauthfrom db_handler import get_db_connection, release_db_connection+ from auth_utils import acquire_first_user_lockimport requests@@ -320,6 +322,10 @@ def oidc_callback_route():if cur.fetchone():username = f"{username}_{str(uuid.uuid4())[:4]}" # Short random suffix+ # AUTH-07: serialize here, before the count that decides+ # owner and admin. Two concurrent first OIDC logins used+ # to both see zero users and both become owners.+ acquire_first_user_lock(cur)cur.execute('SELECT COUNT(*) FROM users')user_count = cur.fetchone()[0]diff --git a/tests/test_a_first_user_race.py b/tests/test_a_first_user_race.pynew file mode 100644index 0000000..c4bb4bf--- /dev/null+++ b/tests/test_a_first_user_race.py@@ -0,0 +1,102 @@+"""AUTH-07: first-user registration race.++Ten concurrent first registrations used to all succeed and leave two+owners. The registration transaction now takes a PostgreSQL advisory+lock before the user-count check, so exactly one becomes owner.++The end-to-end race test below is opportunistic: in-process threads+share the GIL, so the race window is narrow and a run without the fix+can pass by luck. The regression protection is the lock-semantics+test (a second transaction cannot acquire the lock while the first+holds it) plus the source pins (both provisioning paths take it).++The race test file sorts first in the suite (test_a_...) so it can+run against an empty users table, and it deletes the users it+creates, leaving the table empty for the tests that follow. If the+table is not empty (someone runs this file after other tests), it+skips.+"""+import threading+import uuid+from pathlib import Path++import psycopg2+import pytest++from backend.auth_utils import FIRST_USER_LOCK_KEY, acquire_first_user_lock+++def test_first_user_lock_blocks_concurrent_acquire(db_connection):+ """The advisory lock serializes: a second transaction cannot take+ it while the first holds it, and can once the first commits."""+ conn_b = psycopg2.connect(db_connection.dsn)+ try:+ with db_connection.cursor() as cur_a:+ acquire_first_user_lock(cur_a)+ with conn_b.cursor() as cur_b:+ cur_b.execute("SET lock_timeout = '1s'")+ with pytest.raises(psycopg2.errors.LockNotAvailable):+ acquire_first_user_lock(cur_b)+ conn_b.rollback()+ db_connection.commit()+ with conn_b.cursor() as cur_b:+ acquire_first_user_lock(cur_b)+ conn_b.commit()+ finally:+ conn_b.close()+++def test_first_user_lock_taken_by_both_provisioning_paths():+ """Both first-user paths call acquire_first_user_lock before the+ user-count check that decides owner and admin."""+ repo = Path(__file__).resolve().parent.parent+ register = (repo / "backend" / "auth_routes.py").read_text()+ assert "acquire_first_user_lock(cur)" in register+ oidc = (repo / "backend" / "oidc_handler.py").read_text()+ assert "acquire_first_user_lock(cur)" in oidc+++def test_concurrent_first_registrations_mint_one_owner(app, db_connection):+ with db_connection.cursor() as cur:+ cur.execute("SELECT COUNT(*) FROM users")+ if cur.fetchone()[0] != 0:+ pytest.skip(+ "users table is not empty; the race needs a fresh database")+ prefix = "race-" + uuid.uuid4().hex[:8]+ usernames = [f"{prefix}-{i}" for i in range(10)]+ results = {}++ def _register(username):+ # Each thread needs its own test client.+ with app.test_client() as thread_client:+ r = thread_client.post("/api/auth/register", json={+ "username": username,+ "email": f"{username}@test.local",+ "password": "TestPass123!",+ "first_name": "Race",+ "last_name": "User",+ })+ results[username] = r.status_code++ threads = [threading.Thread(target=_register, args=(u,))+ for u in usernames]+ try:+ for thread in threads:+ thread.start()+ for thread in threads:+ thread.join()+ assert len(results) == 10, results+ assert all(code in (200, 201) for code in results.values()), results+ with db_connection.cursor() as cur:+ cur.execute(+ "SELECT COUNT(*) FROM users WHERE username LIKE %s",+ (prefix + "-%",))+ assert cur.fetchone()[0] == 10+ cur.execute("SELECT COUNT(*) FROM users WHERE is_owner = TRUE")+ assert cur.fetchone()[0] == 1+ cur.execute("SELECT COUNT(*) FROM users WHERE is_admin = TRUE")+ assert cur.fetchone()[0] == 1+ finally:+ with db_connection, db_connection.cursor() as cur:+ cur.execute(+ "DELETE FROM users WHERE username LIKE %s", (prefix + "-%",))