🛡️ Warracker is an open source, self-hostable warranty tracker to monitor expirations, store receipts, files. You own the data, your rules!
Security: enforce oidc_only_mode in the backend local auth flows (AUTH-12)
Omega (QA)b8aa825cfd0e
diff --git a/backend/auth_routes.py b/backend/auth_routes.pyindex f2d1f2e..cf25702 100644--- a/backend/auth_routes.py+++ b/backend/auth_routes.py@@ -49,6 +49,24 @@ def _hash_reset_token(token):return hashlib.sha256(token.encode('utf-8')).hexdigest()+# AUTH-12: whether OIDC-only mode is on. Precedence mirrors the OIDC+# handler: the OIDC_ONLY_MODE environment variable wins over the+# site_settings value, which defaults to off. Only-mode is an+# authentication boundary (maintainer ruling D1), so the local auth+# endpoints consult this helper and refuse local flows while it is on.+def _oidc_only_mode_enabled(cur):+ env_value = os.environ.get('OIDC_ONLY_MODE')+ if env_value is not None:+ return env_value.lower() == 'true'+ try:+ cur.execute(+ "SELECT value FROM site_settings WHERE key = 'oidc_only_mode'")+ row = cur.fetchone()+ return bool(row) and row[0].lower() == 'true'+ except Exception:+ return False++@auth_bp.route('/register', methods=['POST'])def register():conn = None@@ -79,7 +97,12 @@ def register():# Check if there are any users (first user can register regardless of setting)cur.execute('SELECT COUNT(*) FROM users')user_count = cur.fetchone()[0]-++ # AUTH-12: OIDC-only mode forbids local registration outright,+ # including the first user, who must be provisioned via OIDC.+ if _oidc_only_mode_enabled(cur):+ return jsonify({'message': 'Local registration is disabled. Please use single sign-on!'}), 403+# If registration is disabled and this is not the first user, return errorif not registration_enabled and user_count > 0:return jsonify({'message': 'Registration is currently disabled!'}), 403@@ -194,6 +217,12 @@ def login():conn = db_handler.get_db_connection()with conn.cursor() as cur:+ # AUTH-12: OIDC-only mode forbids local sign-in outright. The+ # check runs before the password verification, so no local+ # credential is accepted while the mode is on.+ if _oidc_only_mode_enabled(cur):+ return jsonify({'message': 'Local sign-in is disabled. Please use single sign-on!'}), 403+# Check if user exists - include is_admin in the querycur.execute('SELECT id, username, email, password_hash, is_active, is_admin FROM users WHERE username = %s OR email = %s', (username, username))user = cur.fetchone()@@ -374,14 +403,21 @@ def request_password_reset():conn = db_handler.get_db_connection()with conn.cursor() as cur:# Check if user exists- cur.execute('SELECT id FROM users WHERE email = %s', (email,))+ cur.execute('SELECT id, oidc_sub FROM users WHERE email = %s', (email,))user = cur.fetchone()if not user:# Don't reveal if email exists or not for securityreturn jsonify({'message': 'If your email is registered, you will receive a password reset link.'}), 200-+user_id = user[0]++ # AUTH-12: under OIDC-only mode, an OIDC-managed account must+ # never gain a local password from a reset. Answer with the+ # same generic message and mint nothing, so the refusal does+ # not reveal whether the address is registered or SSO-managed.+ if user[1] is not None and _oidc_only_mode_enabled(cur):+ return jsonify({'message': 'If your email is registered, you will receive a password reset link.'}), 200# Generate reset token. Only its hash is stored (AUTH-08), so# the database value alone can never complete a reset; the@@ -714,6 +750,14 @@ def reset_password():return jsonify({'message': 'Invalid or expired token!'}), 400user_id = token_info[0]++ # AUTH-12: a reset token minted before OIDC-only mode was+ # turned on must not complete for an OIDC-managed account.+ # The generic message does not reveal why the token fails.+ cur.execute('SELECT oidc_sub FROM users WHERE id = %s', (user_id,))+ owner = cur.fetchone()+ if owner and owner[0] is not None and _oidc_only_mode_enabled(cur):+ return jsonify({'message': 'Invalid or expired token!'}), 400# Hash the new passwordpassword_hash = bcrypt.generate_password_hash(password).decode('utf-8')diff --git a/tests/test_oidc_only_mode.py b/tests/test_oidc_only_mode.pynew file mode 100644index 0000000..b93f820--- /dev/null+++ b/tests/test_oidc_only_mode.py@@ -0,0 +1,131 @@+"""OIDC-only mode enforcement (AUTH-12, maintainer ruling D1).++With oidc_only_mode on, local sign-in and local registration are+refused outright, and a password reset never mints a local password+for an OIDC-managed account (neither at request time nor at+completion, so a token minted before the mode was turned on cannot+complete either). Local accounts can still request a reset while the+mode is on; the password is usable again if the mode is later turned+off. The mode itself is the escape hatch: an OIDC admin can turn it+off, or it can be cleared with OIDC_ONLY_MODE=false.+"""+import uuid+from contextlib import contextmanager+from datetime import datetime, timedelta, UTC++from backend.auth_routes import _hash_reset_token+++@contextmanager+def only_mode(db_connection, enabled=True):+ with db_connection, db_connection.cursor() as cur:+ cur.execute(+ "INSERT INTO site_settings (key, value) VALUES "+ "('oidc_only_mode', %s) ON CONFLICT (key) DO UPDATE "+ "SET value = EXCLUDED.value",+ ("true" if enabled else "false",),+ )+ try:+ yield+ finally:+ with db_connection, db_connection.cursor() as cur:+ cur.execute(+ "DELETE FROM site_settings WHERE key = 'oidc_only_mode'")+++def _oidc_only_user(db_connection):+ username = f"oidconly_{uuid.uuid4().hex[:8]}"+ with db_connection, db_connection.cursor() as cur:+ cur.execute(+ "INSERT INTO users (username, email, password_hash, oidc_sub, "+ "oidc_issuer, is_active) VALUES (%s, %s, NULL, %s, %s, TRUE) "+ "RETURNING id",+ (username, f"{username}@test.local",+ f"sub-{uuid.uuid4().hex[:12]}", "https://idp.test"),+ )+ return username, f"{username}@test.local", cur.fetchone()[0]+++def _reset_tokens_for(db_connection, user_id):+ with db_connection.cursor() as cur:+ cur.execute(+ "SELECT COUNT(*) FROM password_reset_tokens WHERE user_id = %s",+ (user_id,),+ )+ return cur.fetchone()[0]+++def test_local_login_refused_when_only_mode(+ client, user_factory, db_connection):+ user = user_factory()+ with only_mode(db_connection):+ r = client.post("/api/auth/login", json={+ "username": user["username"], "password": "TestPass123!"})+ assert r.status_code == 403+ assert "single sign-on" in r.get_json()["message"]+ # The mode off again, the same credentials work.+ r = client.post("/api/auth/login", json={+ "username": user["username"], "password": "TestPass123!"})+ assert r.status_code == 200+++def test_local_registration_refused_when_only_mode(client, db_connection):+ with only_mode(db_connection):+ r = client.post("/api/auth/register", json={+ "username": f"local_{uuid.uuid4().hex[:8]}",+ "email": "[email protected]",+ "password": "TestPass123!",+ })+ assert r.status_code == 403+ assert "single sign-on" in r.get_json()["message"]+++def test_reset_mints_nothing_for_oidc_account_when_only_mode(+ client, db_connection):+ _, email, user_id = _oidc_only_user(db_connection)+ with only_mode(db_connection):+ r = client.post("/api/auth/password/reset-request",+ json={"email": email})+ # Same generic message as for an unknown address.+ assert r.status_code == 200+ assert r.get_json()["message"] == (+ "If your email is registered, you will receive a "+ "password reset link.")+ assert _reset_tokens_for(db_connection, user_id) == 0+++def test_reset_still_mints_for_local_account_when_only_mode(+ client, user_factory, db_connection):+ user = user_factory()+ email = f"{user['username']}@test.local"+ with only_mode(db_connection):+ r = client.post("/api/auth/password/reset-request",+ json={"email": email})+ assert r.status_code == 200+ with db_connection.cursor() as cur:+ cur.execute(+ "SELECT id FROM users WHERE email = %s", (email,))+ user_id = cur.fetchone()[0]+ assert _reset_tokens_for(db_connection, user_id) == 1+++def test_reset_completion_refused_for_oidc_account_when_only_mode(+ client, db_connection):+ _, _, user_id = _oidc_only_user(db_connection)+ raw_token = str(uuid.uuid4())+ with db_connection, db_connection.cursor() as cur:+ cur.execute(+ "INSERT INTO password_reset_tokens (user_id, token, expires_at) "+ "VALUES (%s, %s, %s)",+ (user_id, _hash_reset_token(raw_token),+ datetime.now(UTC) + timedelta(hours=1)),+ )+ with only_mode(db_connection):+ r = client.post("/api/auth/password/reset", json={+ "token": raw_token, "password": "NewPass123!"})+ assert r.status_code == 400+ assert r.get_json()["message"] == "Invalid or expired token!"+ # The token is still valid once the mode is off.+ r = client.post("/api/auth/password/reset", json={+ "token": raw_token, "password": "NewPass123!"})+ assert r.status_code == 200