🛡️ Warracker is an open source, self-hostable warranty tracker to monitor expirations, store receipts, files. You own the data, your rules!
Security: confine CSV import row failures with savepoints, make duplicate suffixing linear (CSV-01, CSV-03)
Omega (QA)2046d7422b20
diff --git a/backend/warranties_routes.py b/backend/warranties_routes.pyindex 5a9f2f8..fdff26c 100644--- a/backend/warranties_routes.py+++ b/backend/warranties_routes.py@@ -1576,12 +1576,30 @@ def import_warranties():conn.autocommit = False # Start transactionwith conn.cursor() as cur:+ # CSV-03: next suffix to try per (base name, purchase date).+ # The duplicate search used to restart at (1) for every row,+ # so a same-name import re-checked every earlier suffix for+ # each row: O(n^2) database checks. Resuming where the last+ # row left off makes it O(n); the loop still verifies each+ # candidate against the database, so the renaming result is+ # unchanged.+ next_suffix = {}+for row in csv_reader:row_number += 1 # Increment for each data row (header is row 1)errors = []processed_row = {}try:+ # CSV-01: one savepoint per row. A database error in+ # a row (for example an over-long serial aborting the+ # transaction) used to poison the whole import: the+ # commit at the end rolled everything back while the+ # API still reported the rows imported before the+ # failure. Rolling back to the savepoint confines the+ # failure to its row, so success_count is accurate.+ cur.execute('SAVEPOINT csv_row')+# --- Data Extraction and Basic Validation ---product_name = (row.get('ProductName') or '').strip()purchase_date_str = (row.get('PurchaseDate') or '').strip()@@ -1757,12 +1775,15 @@ def import_warranties():if is_name_taken(product_name):base_name = product_name- suffix_index = 1+ suffix_index = next_suffix.get(+ (base_name, purchase_date), 1)while True:candidate_name = f"{base_name} ({suffix_index})"if not is_name_taken(candidate_name):logger.info(f"[Import] Duplicate detected for row {row_number}. Renaming '{base_name}' to '{candidate_name}' for purchase date {purchase_date}.")product_name = candidate_name+ next_suffix[(base_name, purchase_date)] = (+ suffix_index + 1)breaksuffix_index += 1@@ -1874,11 +1895,18 @@ def import_warranties():used_name_date_pairs.add((product_name, purchase_date))imported_count += 1+ cur.execute('RELEASE SAVEPOINT csv_row')except Exception as e:logger.error(f"Error processing CSV row {row_number}: {e}")failed_rows.append({"row": row_number, "errors": [f"Internal processing error: {str(e)}"]})- # Don't rollback yet, just record failure+ # Roll the failed row back to its savepoint so the+ # transaction stays usable for the remaining rows.+ try:+ cur.execute('ROLLBACK TO SAVEPOINT csv_row')+ cur.execute('RELEASE SAVEPOINT csv_row')+ except Exception as savepoint_err:+ logger.error(f"Error rolling back CSV row {row_number} to savepoint: {savepoint_err}")# --- Transaction Commit/Rollback ---if imported_count > 0 and failed_rows:diff --git a/tests/test_csv_import_integrity.py b/tests/test_csv_import_integrity.pynew file mode 100644index 0000000..1fab8ab--- /dev/null+++ b/tests/test_csv_import_integrity.py@@ -0,0 +1,79 @@+"""CSV import integrity and cost (CSV-01, CSV-03).++CSV-01: one database-error row used to abort the whole import+transaction, so the commit at the end rolled everything back while+the API still reported the rows imported before the failure. Each+row now runs under its own savepoint, so a failed row is confined+to itself and success_count is accurate.++CSV-03: duplicate suffixing restarted at (1) for every row, so a+same-name import re-checked every earlier suffix per row (O(n^2)+database checks). The search now resumes where the last row left+off, which makes it O(n) with identical renaming results.+"""+import io+import time++HEADER = (+ "ProductName,PurchaseDate,IsLifetime,WarrantyDurationYears,"+ "WarrantyDurationMonths,WarrantyDurationDays,ExpirationDate,"+ "Status,PurchasePrice,SerialNumber,ProductURL,Tags,Vendor\n"+)+++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, serial=""):+ return (+ f'"{name}",2025-01-01,FALSE,1,0,0,,"",,{serial},,,Acme\n'+ )+++def test_bad_row_does_not_roll_back_good_rows(+ client, user_factory, db_connection):+ user = user_factory()+ body = HEADER + _row("GoodOne") + _row("BadSerial", "X" * 300) \+ + _row("GoodTwo")+ r = _import(client, user["headers"], body)+ assert r.status_code == 200, r.get_data(as_text=True)+ result = r.get_json()+ assert result["success_count"] == 2, result+ assert result["failure_count"] == 1, result+ assert result["errors"][0]["row"] == 3, result++ # The two good rows actually persisted; the bad one did not.+ with db_connection.cursor() as cur:+ cur.execute(+ "SELECT product_name FROM warranties WHERE user_id = "+ "(SELECT id FROM users WHERE username = %s)",+ (user["username"],))+ names = sorted(row[0] for row in cur.fetchall())+ assert names == ["GoodOne", "GoodTwo"]+++def test_same_name_import_is_linear_time(client, user_factory, db_connection):+ user = user_factory()+ rows = "".join(_row("SameWidget") for _ in range(500))+ started = time.monotonic()+ r = _import(client, user["headers"], HEADER + rows)+ elapsed = time.monotonic() - started+ assert r.status_code == 200, r.get_data(as_text=True)+ result = r.get_json()+ assert result["success_count"] == 500, result+ assert result["failure_count"] == 0, result+ # The pre-fix quadratic scan needed over a minute for 500 rows;+ # the linear scan finishes in seconds even on a slow runner.+ assert elapsed < 30, elapsed++ # Every row got a distinct suffixed name.+ with db_connection.cursor() as cur:+ cur.execute(+ "SELECT COUNT(DISTINCT product_name) FROM warranties "+ "WHERE user_id = (SELECT id FROM users WHERE username = %s)",+ (user["username"],))+ assert cur.fetchone()[0] == 500