Skip to content

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

Security: accept only unambiguous dates in CSV import and claim dates (CSV-04)

Omega (QA)b8833e8eba17
diff --git a/backend/warranties_routes.py b/backend/warranties_routes.py
index fdff26c..90e6f87 100644
--- a/backend/warranties_routes.py
+++ b/backend/warranties_routes.py
@@ -8,7 +8,49 @@ import json
import csv
import io
from dateutil.relativedelta import relativedelta
-from dateutil.parser import parse as date_parse
+
+# CSV-04: explicit allow-list of unambiguous date formats. The CSV
+# importer and the claim endpoints used to accept anything dateutil
+# would parse, so "03/04/2024" silently became March 4 (month-first).
+# Only ISO dates and named-month dates are accepted; anything else is
+# rejected with a clear error naming the accepted formats.
+CSV_DATE_FORMATS = (
+ '%Y-%m-%d', # 2024-03-15
+ '%d %b %Y', # 15 Mar 2024
+ '%d %B %Y', # 15 March 2024
+ '%b %d, %Y', # Mar 15, 2024
+ '%B %d, %Y', # March 15, 2024
+ '%d %b, %Y', # 15 Mar, 2024
+ '%b %d %Y', # Mar 15 2024
+)
+
+
+def parse_unambiguous_date(value):
+ """Parse a date from the explicit allow-list (CSV-04).
+
+ Accepts ISO YYYY-MM-DD and the named-month forms in
+ CSV_DATE_FORMATS. A date object or datetime passes through
+ unchanged (as a date). Anything else, including ambiguous numeric
+ dates such as 03/04/2024, raises ValueError with a message naming
+ the accepted formats.
+ """
+ if isinstance(value, datetime):
+ return value.date()
+ if isinstance(value, date):
+ return value
+ if not isinstance(value, str) or not value.strip():
+ raise ValueError(
+ "Use YYYY-MM-DD or a named month, such as 15 Mar 2024 or "
+ "March 15, 2024.")
+ text = value.strip()
+ for fmt in CSV_DATE_FORMATS:
+ try:
+ return datetime.strptime(text, fmt).date()
+ except ValueError:
+ continue
+ raise ValueError(
+ f"Date '{text}' is ambiguous or unsupported. Use YYYY-MM-DD or "
+ "a named month, such as 15 Mar 2024 or March 15, 2024.")
import mimetypes
from flask import Response
import uuid
@@ -1630,10 +1672,9 @@ def import_warranties():
# --- Type/Format Validation ---
try:
- purchase_date_dt = date_parse(purchase_date_str)
- purchase_date = purchase_date_dt.date()
- except ValueError:
- errors.append("Invalid PurchaseDate format.")
+ purchase_date = parse_unambiguous_date(purchase_date_str)
+ except ValueError as e:
+ errors.append(f"Invalid PurchaseDate format. {e}")
purchase_date = None # Set to None to prevent further errors
is_lifetime = is_lifetime_str == 'true'
@@ -1682,11 +1723,11 @@ def import_warranties():
expiration_date_str
):
try:
- expiration_date = date_parse(expiration_date_str).date()
+ expiration_date = parse_unambiguous_date(expiration_date_str)
if expiration_date < purchase_date:
errors.append("ExpirationDate cannot be before PurchaseDate.")
- except ValueError:
- errors.append("Invalid ExpirationDate format. Use YYYY-MM-DD.")
+ except ValueError as e:
+ errors.append(f"Invalid ExpirationDate format. {e}")
# Existing duration calculation logic
elif (
warranty_duration_years > 0 or
@@ -2658,16 +2699,16 @@ def create_claim(warranty_id):
# Parse dates
try:
- parsed_claim_date = date_parse(claim_date).date() if isinstance(claim_date, str) else claim_date
- except (ValueError, TypeError):
- return jsonify({'error': 'Invalid claim date format'}), 400
+ parsed_claim_date = parse_unambiguous_date(claim_date)
+ except (ValueError, TypeError) as e:
+ return jsonify({'error': f'Invalid claim date format. {e}'}), 400
parsed_resolution_date = None
if resolution_date:
try:
- parsed_resolution_date = date_parse(resolution_date).date() if isinstance(resolution_date, str) else resolution_date
- except (ValueError, TypeError):
- return jsonify({'error': 'Invalid resolution date format'}), 400
+ parsed_resolution_date = parse_unambiguous_date(resolution_date)
+ except (ValueError, TypeError) as e:
+ return jsonify({'error': f'Invalid resolution date format. {e}'}), 400
# Validate status
valid_statuses = ['Submitted', 'In Progress', 'Approved', 'Denied', 'Resolved', 'Cancelled']
@@ -2883,17 +2924,17 @@ def update_claim(warranty_id, claim_id):
# Parse dates
if claim_date:
try:
- parsed_claim_date = date_parse(claim_date).date() if isinstance(claim_date, str) else claim_date
- except (ValueError, TypeError):
- return jsonify({'error': 'Invalid claim date format'}), 400
+ parsed_claim_date = parse_unambiguous_date(claim_date)
+ except (ValueError, TypeError) as e:
+ return jsonify({'error': f'Invalid claim date format. {e}'}), 400
else:
parsed_claim_date = current_claim[0]
if resolution_date:
try:
- parsed_resolution_date = date_parse(resolution_date).date() if isinstance(resolution_date, str) else resolution_date
- except (ValueError, TypeError):
- return jsonify({'error': 'Invalid resolution date format'}), 400
+ parsed_resolution_date = parse_unambiguous_date(resolution_date)
+ except (ValueError, TypeError) as e:
+ return jsonify({'error': f'Invalid resolution date format. {e}'}), 400
else:
parsed_resolution_date = current_claim[5]
diff --git a/tests/test_csv_date_formats.py b/tests/test_csv_date_formats.py
new file mode 100644
index 0000000..a842902
--- /dev/null
+++ b/tests/test_csv_date_formats.py
@@ -0,0 +1,132 @@
+"""CSV-04: explicit allow-list of unambiguous date formats.
+
+Only ISO YYYY-MM-DD and named-month dates are accepted, in the CSV
+importer (PurchaseDate, ExpirationDate) and the claim endpoints
+(claim_date, resolution_date). Ambiguous numeric dates such as
+03/04/2024 are rejected with a clear error naming the accepted
+formats, instead of being silently parsed month-first.
+"""
+import io
+from datetime import date
+
+import pytest
+
+from backend.warranties_routes import parse_unambiguous_date
+
+HEADER = (
+ "ProductName,PurchaseDate,IsLifetime,WarrantyDurationYears,"
+ "WarrantyDurationMonths,WarrantyDurationDays,ExpirationDate,"
+ "Status,PurchasePrice,SerialNumber,ProductURL,Tags,Vendor\n"
+)
+
+
+def test_accepted_formats():
+ assert parse_unambiguous_date("2024-03-15") == date(2024, 3, 15)
+ assert parse_unambiguous_date("15 Mar 2024") == date(2024, 3, 15)
+ assert parse_unambiguous_date("15 March 2024") == date(2024, 3, 15)
+ assert parse_unambiguous_date("Mar 15, 2024") == date(2024, 3, 15)
+ assert parse_unambiguous_date("March 15, 2024") == date(2024, 3, 15)
+ assert parse_unambiguous_date("15 Mar, 2024") == date(2024, 3, 15)
+ assert parse_unambiguous_date("Mar 15 2024") == date(2024, 3, 15)
+ assert parse_unambiguous_date("5 Mar 2024") == date(2024, 3, 5)
+ assert parse_unambiguous_date("15 mar 2024") == date(2024, 3, 15)
+ assert parse_unambiguous_date(" 2024-03-15 ") == date(2024, 3, 15)
+
+
+def test_date_objects_pass_through():
+ assert parse_unambiguous_date(date(2024, 3, 15)) == date(2024, 3, 15)
+
+
+def test_ambiguous_and_unsupported_dates_rejected():
+ for bad in ("03/04/2024", "04/03/2024", "2024/03/15", "15.03.2024",
+ "2024-13-01", "2024-02-30", "March 3 2026x", "", "not a date"):
+ with pytest.raises(ValueError, match="YYYY-MM-DD"):
+ parse_unambiguous_date(bad)
+
+
+def _import(client, headers, body):
+ return client.post(
+ "/api/warranties/import", headers=headers,
+ data={"csv_file": (io.BytesIO(body.encode()), "t.csv")},
+ content_type="multipart/form-data")
+
+
+def _row(name, purchase_date, expiration_date="", duration_years=1):
+ # 13 fields in header order. A row with an explicit expiration date
+ # needs zero duration, or the importer calculates the expiration
+ # from the duration and ignores the provided date.
+ return (f'"{name}",{purchase_date},FALSE,{duration_years},0,0,'
+ f'{expiration_date},"",,,,,,Acme\n')
+
+
+def test_csv_import_accepts_named_month_dates(client, user_factory):
+ user = user_factory()
+ body = HEADER + _row("NamedMonth", "15 Mar 2024")
+ r = _import(client, user["headers"], body)
+ assert r.status_code == 200, r.get_data(as_text=True)
+ assert r.get_json()["success_count"] == 1, r.get_json()
+
+
+def test_csv_import_accepts_named_month_expiration(
+ client, user_factory, db_connection):
+ user = user_factory()
+ body = HEADER + _row("NamedExpiry", "2024-01-01", '"March 15, 2024"',
+ duration_years=0)
+ r = _import(client, user["headers"], body)
+ assert r.status_code == 200, r.get_data(as_text=True)
+ assert r.get_json()["success_count"] == 1, r.get_json()
+ with db_connection.cursor() as cur:
+ cur.execute(
+ "SELECT expiration_date FROM warranties WHERE product_name = %s",
+ ("NamedExpiry",))
+ assert cur.fetchone()[0] == date(2024, 3, 15)
+
+
+def test_csv_import_rejects_ambiguous_numeric_date(client, user_factory):
+ user = user_factory()
+ body = HEADER + _row("Ambiguous", "03/04/2024")
+ r = _import(client, user["headers"], body)
+ # Every row failed, so the endpoint answers 400; the row error
+ # itself must name the accepted formats.
+ assert r.status_code == 400, r.get_data(as_text=True)
+ result = r.get_json()
+ assert result["errors"][0]["errors"][0].startswith(
+ "Invalid PurchaseDate format."), result
+ assert "YYYY-MM-DD" in result["errors"][0]["errors"][0], result
+
+
+def _claim(client, headers, wid, claim_date, resolution_date=None):
+ body = {"claim_date": claim_date, "status": "Submitted"}
+ if resolution_date is not None:
+ body["resolution_date"] = resolution_date
+ return client.post(f"/api/warranties/{wid}/claims",
+ headers=headers, json=body)
+
+
+def test_claim_dates_use_the_same_allow_list(
+ client, user_factory, warranty_factory):
+ h = user_factory()["headers"]
+ wid = warranty_factory(h).get_json()["id"]
+
+ r = _claim(client, h, wid, "03/04/2024")
+ assert r.status_code == 400
+ assert "YYYY-MM-DD" in r.get_json()["error"]
+
+ r = _claim(client, h, wid, "15 Mar 2024",
+ resolution_date="04/05/2024")
+ assert r.status_code == 400
+ assert "YYYY-MM-DD" in r.get_json()["error"]
+
+ r = _claim(client, h, wid, "March 15, 2024",
+ resolution_date="15 Mar 2024")
+ assert r.status_code == 201, r.get_data(as_text=True)
+ cid = r.get_json()["id"]
+
+ r = client.put(f"/api/warranties/{wid}/claims/{cid}", headers=h,
+ json={"claim_date": "03/04/2024"})
+ assert r.status_code == 400
+ assert "YYYY-MM-DD" in r.get_json()["error"]
+
+ r = client.put(f"/api/warranties/{wid}/claims/{cid}", headers=h,
+ json={"claim_date": "15 March 2024"})
+ assert r.status_code == 200, r.get_data(as_text=True)