π‘οΈ Warracker is an open source, self-hostable warranty tracker to monitor expirations, store receipts, files. You own the data, your rules!
Fix authorization bypass on /api/files/ document route; credit reporter
Omega (QA)696f3a2bdd75
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f3fcdf8..e82999d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -13,6 +13,8 @@- _Files: `frontend/js/components/tagManager.js`_### Fixed+- **Insecure direct file access via `/api/files/` fixed (reported by Malik Abdullah):** the legacy `/api/files/<path>` route served any uploaded document to any logged-in user with no ownership check and no regard for the admin's document-sharing (`global_view_enabled`) setting β while `/api/secure-file/` on the same files correctly returned 403. Verified live: with sharing disabled, a second account downloaded another user's invoice via `/api/files/` (200) while `/api/secure-file/` returned 403. Both routes now share a single `_check_file_authorization()` helper (owner, admin, or global-view setting), so they can no longer drift apart; `/api/files/` also gained the path-traversal guard. With sharing enabled (the default, intentional for family/team instances) cross-user access still works consistently on both routes. Credit: reported via responsible disclosure by Malik Abdullah.+ - _Files: `backend/file_routes.py`- **Stored XSS via warranty fields fixed (reported by lazymaster101 and the CSCE 413 Texas A&M team):** warranty cards rendered `product_name`, `vendor`, `model_number`, `warranty_type`, tag names, serial numbers, and the user display name into `innerHTML` without escaping, so a malicious value (e.g. injected through CSV import) executed JavaScript in every viewer's browser. All user-controlled fields are now HTML-escaped before rendering (quotes included, so attribute contexts are safe too), and `product_url` links now also reject `javascript:`/`data:`/`vbscript:` schemes. Verified with live payloads (`<img onerror>`, `<svg onload>`, attribute breakout, `javascript:` URL, malicious tag name) β all render as inert text. Credit: reported via responsible disclosure by [lazymaster101](https://github.com/lazymaster101) and the CSCE 413 (Texas A&M University) vulnerability-research team β Carrigan Royer, Jayani Singh, Seshadithya Saravanan, Aaditya Srinivasan, Miko Quinones.- _Files: `frontend/js/components/warrantyRenderer.js`, `frontend/js/components/claims.js`, `frontend/status.js`_- **Input validations are now enforced and translated:** three new HTTP 400 validations β product name over 255 chars (was an unhandled DB error β HTTP 500), expiration date before purchase date (was silently accepted), and invalid claim status (was silently coerced) β now return a stable machine-readable `code` (`product_name_too_long`, `expiration_before_purchase`, `invalid_claim_status`; claim-status errors also include `valid_statuses`) alongside the English fallback message. The frontend maps those codes to i18n keys via a new `apiErrorMessage()` helper in `ui.js` (used by the add-warranty form, edit modal, and claims toasts), so error toasts render in the user's language instead of always-English. Two new English keys were added (`messages.product_name_too_long`, `messages.invalid_claim_status`) and machine-translated into all 19 non-English locales with `{{statuses}}` placeholder integrity verified. Also removed the now-unused `safeErrorMessage()` helper from `apiService.js`.diff --git a/README.md b/README.mdindex 95d3aa0..703e561 100644--- a/README.md+++ b/README.md@@ -323,6 +323,7 @@ This project is licensed under the GNU Affero General Public License v3.0 - see### Security researchers* [lazymaster101](https://github.com/lazymaster101) and the CSCE 413 (Texas A&M University) vulnerability-research team β Carrigan Royer, Jayani Singh, Seshadithya Saravanan, Aaditya Srinivasan, Miko Quinones β for the responsible disclosure of a stored XSS vulnerability.+* Malik Abdullah β for the responsible disclosure of an authorization bypass on the `/api/files/` document-serving route.## βStar Historydiff --git a/backend/file_routes.py b/backend/file_routes.pyindex 9e5061f..afec4ba 100644--- a/backend/file_routes.py+++ b/backend/file_routes.py@@ -24,6 +24,63 @@ file_bp = Blueprint('file_bp', __name__)# Set up logginglogger = logging.getLogger(__name__)+# ============================+# Shared file authorization+# ============================++def _check_file_authorization(cur, db_search_path, user_id, is_admin):+ """+ Shared authorization check for serving uploaded files.+ db_search_path is the path as stored in the DB (e.g. 'uploads/abc.pdf').+ Returns True when the user may access the file, False otherwise.++ Rules (identical for /files/ and /secure-file/):+ - admins: always allowed+ - the owner of the warranty the file is attached to: allowed+ - anyone else: allowed only for shared document types (product photo,+ invoice, manual) when the admin setting global_view_enabled is true+ (and, if global_view_admin_only is true, only admins)+ Files not linked to any warranty are unauthorized for non-admins.+ """+ query = """+ SELECT w.id, w.user_id+ FROM warranties w+ WHERE w.invoice_path = %s OR w.manual_path = %s OR w.other_document_path = %s OR w.product_photo_path = %s+ """+ cur.execute(query, (db_search_path, db_search_path, db_search_path, db_search_path))+ results = cur.fetchall()++ if is_admin:+ logger.info(f"[FILE_AUTH] Admin access granted for '{db_search_path}'")+ return True++ # Ownership authorization+ for warranty_id_db, warranty_user_id_db in (results or []):+ if warranty_user_id_db == user_id:+ logger.info(f"[FILE_AUTH] Ownership confirmed for warranty_id={warranty_id_db}")+ return True++ # Global view permissions for shared documents (photos, invoices, manuals)+ if results:+ for warranty_id_db, _warranty_user_id_db in results:+ cur.execute('SELECT product_photo_path, invoice_path, manual_path FROM warranties WHERE id = %s', (warranty_id_db,))+ warranty_files = cur.fetchone()+ # Only shared document types participate in global view (not other_document)+ if warranty_files and db_search_path in warranty_files:+ cur.execute("SELECT key, value FROM site_settings WHERE key IN ('global_view_enabled', 'global_view_admin_only')")+ settings = {row[0]: row[1] for row in cur.fetchall()}++ global_view_enabled = settings.get('global_view_enabled', 'true').lower() == 'true'+ admin_only = settings.get('global_view_admin_only', 'false').lower() == 'true'++ if global_view_enabled and (not admin_only or is_admin):+ logger.info(f"[FILE_AUTH] Global view access granted for shared document: '{db_search_path}'")+ return True++ logger.warning(f"[FILE_AUTH] Unauthorized file access attempt: '{db_search_path}' by user {user_id}")+ return False++# ============================# Local File Serving Routes# ============================@@ -31,14 +88,27 @@ logger = logging.getLogger(__name__)@file_bp.route('/files/<path:filename>', methods=['GET', 'POST'])@token_requireddef serve_file(filename):- """Basic secure file serving with authentication."""+ """File serving with the same authorization checks as /secure-file/."""+ conn = Nonetry:logger.info(f"File access request for {filename} by user {request.user['id']}")-+if not filename.startswith('uploads/'):logger.warning(f"Attempted access to non-uploads file: {filename}")return jsonify({"message": "Access denied"}), 403-++ # Security check for path traversal+ if '..' in filename or filename.startswith('/'):+ logger.warning(f"Potential path traversal attempt detected: {filename} by user {request.user['id']}")+ return jsonify({"message": "Invalid file path"}), 400++ conn = get_db_connection()+ with conn.cursor() as cur:+ user_id = request.user['id']+ is_admin = request.user.get('is_admin', False)+ if not _check_file_authorization(cur, filename, user_id, is_admin):+ return jsonify({"message": "You are not authorized to access this file"}), 403+# Remove 'uploads/' prefix for send_from_directoryfile_path = filename[8:] if filename.startswith('uploads/') else filename@@ -46,6 +116,9 @@ def serve_file(filename):except Exception as e:logger.error(f"Error serving file {filename}: {e}")return jsonify({"message": "Error accessing file"}), 500+ finally:+ if conn:+ release_db_connection(conn)@file_bp.route('/secure-file/<path:filename>', methods=['GET', 'POST'])@token_required@@ -75,51 +148,13 @@ def secure_file_access(filename):with conn.cursor() as cur:db_search_path = f"uploads/{filename}"logger.info(f"[SECURE_FILE] Searching DB for paths like: '{db_search_path}' (repr: {repr(db_search_path)})")- query = """- SELECT w.id, w.user_id- FROM warranties w- WHERE w.invoice_path = %s OR w.manual_path = %s OR w.other_document_path = %s OR w.product_photo_path = %s- """- cur.execute(query, (db_search_path, db_search_path, db_search_path, db_search_path))- results = cur.fetchall()- logger.info(f"[SECURE_FILE] DB query results for '{db_search_path}': {results}")user_id = request.user['id']is_admin = request.user.get('is_admin', False)- authorized = is_admin- logger.info(f"[SECURE_FILE] Initial authorization (is_admin={is_admin}): {authorized}")- # Check for ownership authorization- if not authorized and results:- for warranty_id_db, warranty_user_id_db in results:- logger.info(f"[SECURE_FILE] Checking ownership: warranty_id={warranty_id_db}, owner_id={warranty_user_id_db}, current_user_id={user_id}")- if warranty_user_id_db == user_id:- authorized = True- logger.info(f"[SECURE_FILE] Ownership confirmed for warranty_id={warranty_id_db}")- break-- # Check global view permissions for shared documents (photos, invoices, manuals)- if not authorized and results:- for warranty_id_db, warranty_user_id_db in results:- # Check if the requested file is a product photo, invoice, or manual for the given warranty- cur.execute('SELECT product_photo_path, invoice_path, manual_path FROM warranties WHERE id = %s', (warranty_id_db,))- warranty_files = cur.fetchone()- # Check if the file path is one of the globally viewable document types- if warranty_files and db_search_path in warranty_files:- # This is a shared document type - check global view settings- cur.execute("SELECT key, value FROM site_settings WHERE key IN ('global_view_enabled', 'global_view_admin_only')")- settings = {row[0]: row[1] for row in cur.fetchall()}-- global_view_enabled = settings.get('global_view_enabled', 'true').lower() == 'true'- admin_only = settings.get('global_view_admin_only', 'false').lower() == 'true'-- if global_view_enabled and (not admin_only or is_admin):- authorized = True- logger.info(f"[SECURE_FILE] Global view access granted for shared document: {filename}")- break-- if not authorized:- logger.warning(f"[SECURE_FILE] Unauthorized file access attempt: '{filename}' (repr: {repr(filename)}) by user {user_id}. DB results count: {len(results) if results else 'None'}")+ # Shared authorization (same rules as /files/)+ if not _check_file_authorization(cur, db_search_path, user_id, is_admin):+ logger.warning(f"[SECURE_FILE] Unauthorized file access attempt: '{filename}' (repr: {repr(filename)}) by user {user_id}")return jsonify({"message": "You are not authorized to access this file"}), 403upload_dir = current_app.config['UPLOAD_FOLDER']