🛡️ Warracker is an open source, self-hostable warranty tracker to monitor expirations, store receipts, files. You own the data, your rules!
Security: settings key allow-list, Apprise audit masking, ownership transfer audit (D3 residuals)
Omega (QA)8e057a74d3b2
diff --git a/backend/admin_routes.py b/backend/admin_routes.pyindex 45e4fd4..6237ffe 100644--- a/backend/admin_routes.py+++ b/backend/admin_routes.py@@ -333,8 +333,13 @@ def transfer_ownership():return jsonify({"message": "Ownership transfer feature is not available. Please run the database migration first."}), 500conn.commit()-+logger.info(f"Ownership successfully transferred from {current_owner_id} to {new_owner_id}.")+ # Audit the transfer (D3 residual): it changes is_owner on+ # two accounts and previously wrote no audit entry.+ create_audit_log('TRANSFER_OWNERSHIP', target_type='User',+ target_id=new_owner_id,+ details=f'Ownership transferred from user {current_owner_id} to user {new_owner_id}')return jsonify({"message": "Ownership transferred successfully."}), 200except Exception as e:@@ -369,6 +374,59 @@ def fix_owner_role():logger.error(f"Error in fix_owner_role endpoint: {e}")return jsonify({'success': False, 'message': 'Failed to fix the owner role. Check the server logs for details.'}), 500+# Site setting keys the settings endpoint accepts (D3 residual). Any+# other key in a PUT body is ignored and reported, so junk or+# pre-seeded keys no longer persist silently. This is the union of+# the keys the backend reads (direct queries, get_site_setting, and+# the settings defaults), the keys the settings UI sends, and the+# legacy admin_oidc_group key the OIDC handler still reads. Add a key+# here before any new setting is written through this endpoint.+SITE_SETTING_KEYS = frozenset({+ 'registration_enabled',+ 'email_base_url',+ 'global_view_enabled',+ 'global_view_admin_only',+ 'oidc_enabled',+ 'oidc_only_mode',+ 'oidc_skip_login_screen',+ 'oidc_provider_name',+ 'oidc_client_id',+ 'oidc_client_secret',+ 'oidc_issuer_url',+ 'oidc_scope',+ 'oidc_admin_group',+ 'admin_oidc_group',+ 'apprise_enabled',+ 'apprise_urls',+ 'apprise_expiration_days',+ 'apprise_notification_time',+ 'apprise_notification_mode',+ 'apprise_warranty_scope',+ 'apprise_title_prefix',+ 'paperless_enabled',+ 'paperless_url',+ 'paperless_api_token',+})++# Setting keys whose values must never appear in audit entries, beyond+# the substring heuristic below. Apprise URLs embed credentials in the+# URL itself (tokens, webhook ids, userinfo), and the key name matches+# none of the heuristic substrings, so rotated credentials used to+# persist in cleartext in historical audit entries (D3 residual).+_SENSITIVE_SETTING_KEYS = frozenset({'apprise_urls'})+++def _setting_value_for_audit(key, value):+ """Mask a setting value for an audit entry, or return it as-is."""+ key_lower = str(key).lower()+ if (key in _SENSITIVE_SETTING_KEYS+ or 'secret' in key_lower+ or 'token' in key_lower+ or 'password' in key_lower):+ return '********'+ return value++# ============================# Site Settings Routes# ============================@@ -505,8 +563,17 @@ def update_site_settings():# Update settingsupdated_keys = []+ ignored_keys = []requires_restart = Falsefor key, value in data.items():+ # Unknown keys are ignored, not persisted: without an+ # allow-list, junk keys used to land in site_settings+ # silently (D3 residual). Known keys still save.+ if key not in SITE_SETTING_KEYS:+ ignored_keys.append(key)+ logger.warning(f"Ignoring unknown site setting key: {key}")+ continue+# Sanitize boolean-like string valuesif key in ['registration_enabled', 'oidc_enabled', 'oidc_only_mode', 'oidc_skip_login_screen', 'global_view_enabled', 'global_view_admin_only', 'paperless_enabled']:value = 'true' if str(value).lower() == 'true' else 'false'@@ -556,18 +623,20 @@ def update_site_settings():elif requires_restart: # This case might be redundant if all oidc_ keys trigger the aboveresponse_message += " An application restart is required for some settings to take full effect."- # Audit log for updated settings (mask sensitive values)+ # Audit log for updated settings (mask sensitive values).+ # Only persisted keys are audited; ignored keys get no+ # entry, since nothing was stored for them.try:- for key, val in data.items():- masked_val = val- key_lower = str(key).lower()- if 'secret' in key_lower or 'token' in key_lower or 'password' in key_lower:- masked_val = '********'+ for key in updated_keys:+ masked_val = _setting_value_for_audit(key, data[key])create_audit_log('UPDATE_SETTING', target_type='SiteSetting', target_id=key, details=f'Set {key} to {masked_val}')except Exception as audit_err:logger.warning(f"Failed to write audit logs for settings update: {audit_err}")- return jsonify({"message": response_message}), 200+ response_body = {"message": response_message}+ if ignored_keys:+ response_body["ignored_keys"] = ignored_keys+ return jsonify(response_body), 200except Exception as e:logger.error(f"Error updating site settings: {e}")if conn:diff --git a/tests/test_settings_allowlist_audit.py b/tests/test_settings_allowlist_audit.pynew file mode 100644index 0000000..f9a3c5c--- /dev/null+++ b/tests/test_settings_allowlist_audit.py@@ -0,0 +1,185 @@+"""D3 residuals: the settings endpoint allow-list, Apprise audit+masking, and the ownership-transfer audit entry.+"""+import pytest++from backend.admin_routes import SITE_SETTING_KEYS, _setting_value_for_audit+++def _promote(db_connection, username, owner=False):+ with db_connection, db_connection.cursor() as cur:+ cur.execute(+ "UPDATE users SET is_admin = TRUE, is_owner = %s "+ "WHERE username = %s", (owner, username))+++def _max_audit_id(db_connection):+ with db_connection.cursor() as cur:+ cur.execute("SELECT COALESCE(MAX(id), 0) FROM audit_log")+ return cur.fetchone()[0]+++def _new_audit_rows(db_connection, action, before_id):+ with db_connection.cursor() as cur:+ cur.execute(+ "SELECT target_type, target_id, details FROM audit_log "+ "WHERE action = %s AND id > %s ORDER BY id",+ (action, before_id))+ return cur.fetchall()+++def _setting_value(db_connection, key):+ with db_connection.cursor() as cur:+ cur.execute("SELECT value FROM site_settings WHERE key = %s", (key,))+ row = cur.fetchone()+ return row[0] if row else None+++def restore_settings(db_connection):+ """Restore the touched settings rows after the test."""+ keys = ["email_base_url", "apprise_urls"]+ before = {key: _setting_value(db_connection, key) for key in keys}+ yield+ with db_connection, db_connection.cursor() as cur:+ for key, value in before.items():+ if value is None:+ cur.execute(+ "DELETE FROM site_settings WHERE key = %s", (key,))+ else:+ cur.execute(+ "INSERT INTO site_settings (key, value) VALUES (%s, %s) "+ "ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value",+ (key, value))+++def test_allow_list_covers_every_known_key():+ for key in (+ "registration_enabled",+ "email_base_url",+ "global_view_enabled",+ "global_view_admin_only",+ "oidc_enabled",+ "oidc_only_mode",+ "oidc_skip_login_screen",+ "oidc_provider_name",+ "oidc_client_id",+ "oidc_client_secret",+ "oidc_issuer_url",+ "oidc_scope",+ "oidc_admin_group",+ "admin_oidc_group",+ "apprise_enabled",+ "apprise_urls",+ "apprise_expiration_days",+ "apprise_notification_time",+ "apprise_notification_mode",+ "apprise_warranty_scope",+ "apprise_title_prefix",+ "paperless_enabled",+ "paperless_url",+ "paperless_api_token",+ ):+ assert key in SITE_SETTING_KEYS+ assert "junk_key" not in SITE_SETTING_KEYS+++def test_unknown_keys_ignored_and_reported(+ client, admin_user, db_connection, restore_settings):+ _promote(db_connection, admin_user["username"])+ before = _max_audit_id(db_connection)+ r = client.put(+ "/api/admin/settings", headers=admin_user["headers"], json={+ "email_base_url": "https://warracker.example",+ "junk_key": "persist-me",+ "another_junk": "1",+ })+ assert r.status_code == 200, r.get_data(as_text=True)+ assert sorted(r.get_json()["ignored_keys"]) == [+ "another_junk", "junk_key"]+ assert _setting_value(db_connection, "email_base_url") == \+ "https://warracker.example"+ assert _setting_value(db_connection, "junk_key") is None+ assert _setting_value(db_connection, "another_junk") is None+ rows = _new_audit_rows(db_connection, "UPDATE_SETTING", before)+ assert [row[1] for row in rows] == ["email_base_url"]+++def test_known_keys_save_without_ignored_keys_field(+ client, admin_user, db_connection, restore_settings):+ _promote(db_connection, admin_user["username"])+ r = client.put(+ "/api/admin/settings", headers=admin_user["headers"], json={+ "email_base_url": "https://warracker.example"})+ assert r.status_code == 200+ assert "ignored_keys" not in r.get_json()+++def test_audit_masking_covers_apprise_urls_and_secrets():+ assert _setting_value_for_audit(+ "apprise_urls", "tgram://SECRETTOKEN/12345") == "********"+ assert _setting_value_for_audit(+ "oidc_client_secret", "shh") == "********"+ assert _setting_value_for_audit(+ "paperless_api_token", "tok") == "********"+ assert _setting_value_for_audit(+ "smtp_password", "pw") == "********"+ assert _setting_value_for_audit(+ "email_base_url", "https://warracker.example") == \+ "https://warracker.example"+++def test_apprise_urls_masked_in_audit_entry(+ client, admin_user, db_connection, restore_settings):+ _promote(db_connection, admin_user["username"])+ before = _max_audit_id(db_connection)+ r = client.put(+ "/api/admin/settings", headers=admin_user["headers"], json={+ "apprise_urls": "tgram://SECRETTOKEN/12345"})+ assert r.status_code == 200, r.get_data(as_text=True)+ rows = _new_audit_rows(db_connection, "UPDATE_SETTING", before)+ assert len(rows) == 1+ assert rows[0][1] == "apprise_urls"+ assert "SECRETTOKEN" not in rows[0][2]+ assert "********" in rows[0][2]+++def _user_id(db_connection, username):+ with db_connection.cursor() as cur:+ cur.execute("SELECT id FROM users WHERE username = %s", (username,))+ return cur.fetchone()[0]+++def test_ownership_transfer_writes_audit_entry(+ client, user_factory, db_connection):+ current_owner = user_factory()+ new_owner = user_factory()+ _promote(db_connection, current_owner["username"], owner=True)+ _promote(db_connection, new_owner["username"])+ current_id = _user_id(db_connection, current_owner["username"])+ new_id = _user_id(db_connection, new_owner["username"])++ before = _max_audit_id(db_connection)+ r = client.post(+ "/api/admin/transfer-ownership",+ headers=current_owner["headers"], json={"new_owner_id": new_id})+ assert r.status_code == 200, r.get_data(as_text=True)++ rows = _new_audit_rows(db_connection, "TRANSFER_OWNERSHIP", before)+ assert len(rows) == 1+ target_type, target_id, details = rows[0]+ assert target_type == "User"+ assert target_id == str(new_id)+ assert str(current_id) in details and str(new_id) in details++ with db_connection.cursor() as cur:+ cur.execute("SELECT is_owner FROM users WHERE id = %s", (new_id,))+ assert cur.fetchone()[0] is True+ cur.execute("SELECT is_owner FROM users WHERE id = %s", (current_id,))+ assert cur.fetchone()[0] is False++ # Transfer back so later tests still see an owner in place.+ r = client.post(+ "/api/admin/transfer-ownership",+ headers=new_owner["headers"], json={"new_owner_id": current_id})+ assert r.status_code == 200, r.get_data(as_text=True)