Skip to content

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

Fix same-second upload collision and return 413 for oversized uploads

Omega (QA)e4375b327549
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 77be430..5efb030 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -13,6 +13,10 @@
- _Files: `frontend/js/components/tagManager.js`_
### Fixed
+- **Same-second file-upload collision fixed:** stored upload filenames used a second-resolution timestamp only, so two uploads of the same filename within one second shared a storage path and the second overwrote the first. Filenames now include a random suffix (`unique_upload_filename()` helper, applied to invoice/manual/photo/other-document uploads in both add and update). Found by the daily QA sweep.
+ - _Files: `backend/warranties_routes.py`
+- **Oversized uploads now return HTTP 413 instead of 500/dropped connection:** files over `MAX_CONTENT_LENGTH` raised `RequestEntityTooLarge`, which was swallowed into 500s by the generic `except` blocks in the warranty write endpoints and the `token_required` decorator. Added an app-wide 413 handler returning a JSON error naming the configured limit, and both layers now let HTTP exceptions propagate. Found by the daily QA sweep.
+ - _Files: `backend/__init__.py`, `backend/auth_utils.py`, `backend/warranties_routes.py`
- **Tag create/rename 500 on names over 50 characters fixed:** `tags.name` is `varchar(50)`, but neither `POST /api/tags` nor `PUT /api/tags/<id>` validated length, so a 51+ character name escaped as HTTP 500. Both endpoints now return HTTP 400 up front. Found by the daily QA sweep.
- _Files: `backend/tags_routes.py`
- **`saveThemePreference is not defined` ReferenceError on status.html fixed:** the prefs loader in `script.js` called the global `saveThemePreference()`, which is only defined by the `js/lib/theme.js` ES module loaded on index.html. Every status-page load logged a console error and aborted the prefs sync, so saved filters, expiring-soon days, and date format were never written to localStorage there. The call is now guarded with a `typeof` check. Found by the daily QA sweep.
diff --git a/backend/__init__.py b/backend/__init__.py
index 98379d8..a868050 100644
--- a/backend/__init__.py
+++ b/backend/__init__.py
@@ -2,7 +2,7 @@
import os
import logging
import psycopg2.errors
-from flask import Flask, jsonify
+from flask import Flask, jsonify, current_app
from werkzeug.middleware.proxy_fix import ProxyFix
logger = logging.getLogger(__name__)
@@ -235,6 +235,16 @@ def create_app(config_name=None):
logger.info("Application factory completed successfully")
+ @app.errorhandler(413)
+ def request_entity_too_large(e):
+ """Return a JSON 413 when an upload exceeds MAX_CONTENT_LENGTH.
+
+ Without this, oversized uploads surface as HTML error pages or get
+ swallowed into 500s by routes with generic except blocks.
+ """
+ limit_mb = current_app.config.get('MAX_CONTENT_LENGTH', 0) // (1024 * 1024)
+ return jsonify({"error": f"File too large. Maximum upload size is {limit_mb}MB."}), 413
+
@app.route('/api/health', methods=['GET'])
def health_check():
"""Unauthenticated health check for Docker HEALTHCHECK / load balancers.
diff --git a/backend/auth_utils.py b/backend/auth_utils.py
index a7d5aaa..bd27a8e 100644
--- a/backend/auth_utils.py
+++ b/backend/auth_utils.py
@@ -3,6 +3,7 @@ import jwt
from datetime import datetime, UTC, timedelta
from flask import current_app, request, jsonify
from functools import wraps
+from werkzeug.exceptions import HTTPException
import re
# IMPORTANT: We need to import db_handler here for the decorators
@@ -96,6 +97,10 @@ def token_required(f):
})
return f(*args, **kwargs)
+ except HTTPException:
+ # Let HTTP errors (e.g. 413 from oversized uploads) propagate to
+ # the app's error handlers instead of being masked as a 500 here.
+ raise
except Exception as e:
current_app.logger.error(f"Authentication error: {e}")
return jsonify({'message': 'Authentication error!'}), 500
diff --git a/backend/warranties_routes.py b/backend/warranties_routes.py
index e08517f..bff7e97 100644
--- a/backend/warranties_routes.py
+++ b/backend/warranties_routes.py
@@ -11,6 +11,8 @@ from dateutil.relativedelta import relativedelta
from dateutil.parser import parse as date_parse
import mimetypes
from flask import Response
+import uuid
+from werkzeug.exceptions import RequestEntityTooLarge
# Add pytz import for timezone functionality
import pytz
@@ -33,6 +35,17 @@ logger = logging.getLogger(__name__)
warranties_bp = Blueprint('warranties_bp', __name__)
+def unique_upload_filename(original_name, infix=""):
+ """Build a collision-proof stored filename.
+
+ The old scheme used a second-resolution timestamp only, so two uploads of
+ the same filename within one second overwrote each other. A random suffix
+ closes that window.
+ """
+ safe = secure_filename(original_name)
+ stamp = datetime.now().strftime('%Y%m%d%H%M%S')
+ return f"{stamp}_{uuid.uuid4().hex[:8]}_{infix}{safe}"
+
# Map of currency symbols to ISO codes (mirrors frontend js/lib/currency.js).
# Used to resolve a user's preferred currency symbol to a code for new warranties.
SYMBOL_TO_CURRENCY_CODE = {
@@ -380,8 +393,7 @@ def add_warranty():
if not allowed_file(invoice.filename):
return jsonify({"error": "File type not allowed. Use PDF, PNG, JPG, or JPEG"}), 400
- filename = secure_filename(invoice.filename)
- filename = f"{datetime.now().strftime('%Y%m%d%H%M%S')}_{filename}"
+ filename = unique_upload_filename(invoice.filename)
invoice_path = os.path.join(current_app.config['UPLOAD_FOLDER'], filename)
logger.info(f"Attempting to save invoice to: {invoice_path}")
@@ -404,8 +416,7 @@ def add_warranty():
if not allowed_file(manual.filename):
return jsonify({"error": "File type not allowed. Use PDF, PNG, JPG, or JPEG"}), 400
- filename = secure_filename(manual.filename)
- filename = f"{datetime.now().strftime('%Y%m%d%H%M%S')}_manual_{filename}"
+ filename = unique_upload_filename(manual.filename, "manual_")
manual_path = os.path.join(current_app.config['UPLOAD_FOLDER'], filename)
logger.info(f"Attempting to save manual to: {manual_path}")
try:
@@ -426,8 +437,7 @@ def add_warranty():
if not allowed_file(other_document.filename):
return jsonify({"error": "File type not allowed for other document. Use PDF, PNG, JPG, JPEG, ZIP, or RAR"}), 400
- filename = secure_filename(other_document.filename)
- filename = f"{datetime.now().strftime('%Y%m%d%H%M%S')}_other_{filename}"
+ filename = unique_upload_filename(other_document.filename, "other_")
other_document_path_on_disk = os.path.join(current_app.config['UPLOAD_FOLDER'], filename)
logger.info(f"Attempting to save other_document to: {other_document_path_on_disk}")
try:
@@ -449,8 +459,7 @@ def add_warranty():
if not (product_photo.filename.lower().endswith(('.png', '.jpg', '.jpeg', '.webp', '.gif'))):
return jsonify({"error": "Product photo must be an image file (PNG, JPG, JPEG, WEBP, GIF)"}), 400
- filename = secure_filename(product_photo.filename)
- filename = f"{datetime.now().strftime('%Y%m%d%H%M%S')}_photo_{filename}"
+ filename = unique_upload_filename(product_photo.filename, "photo_")
product_photo_path_on_disk = os.path.join(current_app.config['UPLOAD_FOLDER'], filename)
logger.info(f"Attempting to save product_photo to: {product_photo_path_on_disk}")
try:
@@ -517,6 +526,9 @@ def add_warranty():
'id': warranty_id
}), 201
+ except RequestEntityTooLarge:
+ # Let the app-wide 413 handler produce the JSON response
+ raise
except Exception as e:
logger.error(f"Error adding warranty: {e}")
if conn:
@@ -831,8 +843,7 @@ def update_warranty(warranty_id):
logger.info(f"Deleted old invoice: {full_path}")
except Exception as e:
logger.error(f"Error deleting old invoice: {e}")
- filename = secure_filename(invoice.filename)
- filename = f"{datetime.now().strftime('%Y%m%d%H%M%S')}_{filename}"
+ filename = unique_upload_filename(invoice.filename)
invoice_path = os.path.join(current_app.config['UPLOAD_FOLDER'], filename)
logger.info(f"Attempting to save updated invoice to: {invoice_path}")
try:
@@ -886,8 +897,7 @@ def update_warranty(warranty_id):
logger.info(f"Deleted old manual: {full_path}")
except Exception as e:
logger.error(f"Error deleting old manual: {e}")
- filename = secure_filename(manual.filename)
- filename = f"{datetime.now().strftime('%Y%m%d%H%M%S')}_manual_{filename}"
+ filename = unique_upload_filename(manual.filename, "manual_")
manual_path = os.path.join(current_app.config['UPLOAD_FOLDER'], filename)
logger.info(f"Attempting to save updated manual to: {manual_path}")
try:
@@ -941,8 +951,7 @@ def update_warranty(warranty_id):
logger.info(f"Deleted old other_document: {full_path}")
except Exception as e:
logger.error(f"Error deleting old other_document: {e}")
- filename = secure_filename(other_document.filename)
- filename = f"{datetime.now().strftime('%Y%m%d%H%M%S')}_other_{filename}"
+ filename = unique_upload_filename(other_document.filename, "other_")
other_document_path_on_disk = os.path.join(current_app.config['UPLOAD_FOLDER'], filename)
logger.info(f"Attempting to save updated other_document to: {other_document_path_on_disk}")
try:
@@ -1000,8 +1009,7 @@ def update_warranty(warranty_id):
except Exception as e:
logger.error(f"Error deleting old product_photo: {e}")
- filename = secure_filename(product_photo.filename)
- filename = f"{datetime.now().strftime('%Y%m%d%H%M%S')}_photo_{filename}"
+ filename = unique_upload_filename(product_photo.filename, "photo_")
product_photo_path_on_disk = os.path.join(current_app.config['UPLOAD_FOLDER'], filename)
logger.info(f"Attempting to save updated product_photo to: {product_photo_path_on_disk}")
try:
@@ -1150,6 +1158,9 @@ def update_warranty(warranty_id):
return jsonify({"message": "Warranty updated successfully"}), 200
+ except RequestEntityTooLarge:
+ # Let the app-wide 413 handler produce the JSON response
+ raise
except Exception as e:
logger.error(f"Error updating warranty: {e}")
if conn: