🛡️ Warracker is an open source, self-hostable warranty tracker to monitor expirations, store receipts, files. You own the data, your rules!
Add missing 1.0.7 tests and fix CSV import autocommit pool leak
sassanix53aa04e5432f
diff --git a/backend/db_handler.py b/backend/db_handler.pyindex 0070621..d12211b 100644--- a/backend/db_handler.py+++ b/backend/db_handler.py@@ -230,6 +230,12 @@ def release_db_connection(conn):except Exception as e:logger.warning(f"[DB_HANDLER] Rollback on release failed, discarding connection: {e}")broken = True+ if not broken and conn.autocommit:+ try:+ conn.autocommit = False+ except Exception as e:+ logger.warning(f"[DB_HANDLER] Resetting autocommit on release failed, discarding connection: {e}")+ broken = Truethe_pool.putconn(conn, close=broken)except Exception as e:logger.error(f"[DB_HANDLER] Error releasing connection to pool: {e}. Discarding it.")diff --git a/backend/warranties_routes.py b/backend/warranties_routes.pyindex 5cb1d50..4cd683b 100644--- a/backend/warranties_routes.py+++ b/backend/warranties_routes.py@@ -2000,8 +2000,7 @@ def import_warranties():return jsonify({"error": f"Failed to import CSV: {str(e)}"}), 500finally:if conn:- conn.autocommit = True # Reset autocommit- release_db_connection(conn)+ release_db_connection(conn)@warranties_bp.route('/admin/warranties', methods=['GET'])@admin_requireddiff --git a/tests/test_compose_cfg05.py b/tests/test_compose_cfg05.pyindex 4b73f68..6951a02 100644--- a/tests/test_compose_cfg05.py+++ b/tests/test_compose_cfg05.py@@ -29,3 +29,17 @@ def test_docker_compose_env_indentation_and_secret_var():src = "\n".join(lines)assert "SECRET_KEY=${SECRET_KEY:-}" in srcassert "APP_SECRET_KEY" not in src+++def test_root_compose_does_not_mount_missing_init_sql():+ with open(os.path.join(REPO_ROOT, "docker-compose.yml"),+ encoding="utf-8") as fh:+ src = fh.read()+ assert "init.sql" not in src+++def test_nginx_suppresses_version_banner():+ with open(os.path.join(REPO_ROOT, "nginx.conf"),+ encoding="utf-8") as fh:+ src = fh.read()+ assert "server_tokens off;" in srcdiff --git a/tests/test_csv_date_formats.py b/tests/test_csv_date_formats.pyindex 9712b7a..68eb88a 100644--- a/tests/test_csv_date_formats.py+++ b/tests/test_csv_date_formats.py@@ -132,3 +132,27 @@ def test_claim_dates_use_the_same_allow_list(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)++ r = client.put(f"/api/warranties/{wid}/claims/{cid}", headers=h,+ json={"claim_date": "March 15 2024",+ "resolution_date": "15 March, 2024"})+ assert r.status_code == 200, r.get_data(as_text=True)+++def test_csv_import_accepts_full_month_commaless_and_day_comma_dates(+ client, user_factory, db_connection):+ user = user_factory()+ body = (+ HEADER+ + _row("CommalessFullMonth", "March 15 2024", '"15 March, 2026"',+ 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 purchase_date, expiration_date FROM warranties "+ "WHERE product_name = %s",+ ("CommalessFullMonth",))+ assert cur.fetchone() == (date(2024, 3, 15), date(2026, 3, 15))diff --git a/tests/test_csv_formula_neutralization.py b/tests/test_csv_formula_neutralization.pyindex d22b741..f6c7482 100644--- a/tests/test_csv_formula_neutralization.py+++ b/tests/test_csv_formula_neutralization.py@@ -89,3 +89,30 @@ def test_neutralize_csv_formula_behavior_in_both_exporters():capture_output=True, text=True,)assert r.returncode == 0, f"{name}: {r.stderr}"+++def test_csv_import_strips_tab_neutralization_prefix_on_round_trip(+ client, user_factory, db_connection):+ import io+ user = user_factory()+ csv_body = (+ "ProductName,PurchaseDate,IsLifetime,WarrantyDurationYears,"+ "WarrantyDurationMonths,WarrantyDurationDays,ExpirationDate,"+ "Status,PurchasePrice,SerialNumber,ProductURL,Tags,Vendor\n"+ '"\t=SUM(1,2)",2025-01-15,FALSE,1,0,0,,"",,,,,"\t+Acme"\n'+ )+ r = client.post(+ "/api/warranties/import",+ headers=user["headers"],+ data={"csv_file": (io.BytesIO(csv_body.encode("utf-8")), "export.csv")},+ content_type="multipart/form-data",+ )+ assert r.status_code == 200, r.get_data(as_text=True)+ assert r.get_json()["success_count"] == 1+ with db_connection.cursor() as cur:+ cur.execute(+ "SELECT product_name, vendor FROM warranties WHERE product_name = %s",+ ("=SUM(1,2)",),+ )+ row = cur.fetchone()+ assert row == ("=SUM(1,2)", "+Acme")diff --git a/tests/test_db_pool_hardening.py b/tests/test_db_pool_hardening.pynew file mode 100644index 0000000..552482e--- /dev/null+++ b/tests/test_db_pool_hardening.py@@ -0,0 +1,207 @@+"""Database connection pool hardening and early auth release (PR #297).++Covers the pool and decorator hardening introduced in 1.0.7:+- _env_number validation and fallback for DB_POOL_MAX/MIN/WAIT_SECONDS.+- release_db_connection: None no-op, double-release idempotency,+ open-transaction rollback, and closed-connection slot recovery.+- get_db_connection: bounded waiting on pool exhaustion, wake-up when a+ connection returns, and rebuilding a closed pool on retry.+- token_required: releases its auth DB connection before running the+ route, returns JSON 500 on unhandled route errors, and propagates+ HTTPException unchanged.+"""+import threading+import time++import psycopg2+import pytest+from flask import Flask, abort, jsonify+from psycopg2 import extensions, pool++from backend import auth_utils, db_handler+++def test_env_number_validation(monkeypatch):+ monkeypatch.delenv("TEST_POOL_NUM", raising=False)+ assert db_handler._env_number("TEST_POOL_NUM", 4, int, 1) == 4++ monkeypatch.setenv("TEST_POOL_NUM", "10")+ assert db_handler._env_number("TEST_POOL_NUM", 4, int, 1) == 10++ monkeypatch.setenv("TEST_POOL_NUM", "2.5")+ assert db_handler._env_number("TEST_POOL_NUM", 30.0, float, 0) == 2.5++ for bad in ("", " ", "abc", "0", "-3"):+ monkeypatch.setenv("TEST_POOL_NUM", bad)+ assert db_handler._env_number("TEST_POOL_NUM", 4, int, 1) == 4, bad++ for bad_float in ("nan", "inf", "-inf", "-0.1", "not-a-float"):+ monkeypatch.setenv("TEST_POOL_NUM", bad_float)+ assert db_handler._env_number("TEST_POOL_NUM", 30.0, float, 0) == 30.0, bad_float+++def test_release_db_connection_none_and_double_release(app):+ # None is a safe no-op.+ db_handler.release_db_connection(None)++ conn = db_handler.get_db_connection()+ assert id(conn) in db_handler._checked_out+ db_handler.release_db_connection(conn)+ assert id(conn) not in db_handler._checked_out++ # Second release must be ignored without raising or over-releasing slots.+ db_handler.release_db_connection(conn)++ # Pool still hands out and returns DB_POOL_MAX connections cleanly.+ held = [db_handler.get_db_connection() for _ in range(db_handler.DB_POOL_MAX)]+ try:+ assert len(held) == db_handler.DB_POOL_MAX+ finally:+ for c in held:+ db_handler.release_db_connection(c)+++def test_release_rolls_back_open_transaction(app):+ conn = db_handler.get_db_connection()+ try:+ with conn.cursor() as cur:+ cur.execute("SELECT 1")+ assert conn.info.transaction_status == extensions.TRANSACTION_STATUS_INTRANS+ finally:+ db_handler.release_db_connection(conn)++ # Next checkout must see an idle, usable connection.+ conn2 = db_handler.get_db_connection()+ try:+ assert conn2.info.transaction_status == extensions.TRANSACTION_STATUS_IDLE+ with conn2.cursor() as cur:+ cur.execute("SELECT 1")+ assert cur.fetchone()[0] == 1+ conn2.rollback()+ finally:+ db_handler.release_db_connection(conn2)+++def test_release_resets_autocommit_to_false(app):+ conn = db_handler.get_db_connection()+ conn.autocommit = True+ db_handler.release_db_connection(conn)++ # Every connection in the pool must now have autocommit=False.+ held = [db_handler.get_db_connection() for _ in range(db_handler.DB_POOL_MAX)]+ try:+ assert all(not c.autocommit for c in held)+ finally:+ for c in held:+ db_handler.release_db_connection(c)+++def test_release_discards_closed_connection_without_leaking_slot(app):+ conn = db_handler.get_db_connection()+ conn.close()+ assert conn.closed+ db_handler.release_db_connection(conn)++ # Every slot must still be acquirable after discarding a closed connection.+ held = [db_handler.get_db_connection() for _ in range(db_handler.DB_POOL_MAX)]+ try:+ for c in held:+ assert not c.closed+ finally:+ for c in held:+ db_handler.release_db_connection(c)+++def test_pool_exhaustion_waits_and_times_out_or_succeeds(app, monkeypatch):+ monkeypatch.setattr(db_handler, "DB_POOL_WAIT_SECONDS", 0.25)+ held = [db_handler.get_db_connection() for _ in range(db_handler.DB_POOL_MAX)]+ try:+ start = time.monotonic()+ with pytest.raises(pool.PoolError, match="exhausted"):+ db_handler.get_db_connection()+ elapsed = time.monotonic() - start+ assert elapsed >= 0.2++ # Now release one slot mid-wait: the waiter must succeed cleanly.+ monkeypatch.setattr(db_handler, "DB_POOL_WAIT_SECONDS", 2.0)+ to_release = held.pop()++ def _release_later():+ time.sleep(0.15)+ db_handler.release_db_connection(to_release)++ t = threading.Thread(target=_release_later)+ t.start()+ acquired = db_handler.get_db_connection()+ t.join(timeout=5)+ try:+ assert not acquired.closed+ finally:+ db_handler.release_db_connection(acquired)+ finally:+ for c in held:+ db_handler.release_db_connection(c)+++def test_closed_pool_rebuilds_on_retry(app):+ # Ensure a pool exists, then close it to simulate a reset/closed pool.+ c0 = db_handler.get_db_connection()+ db_handler.release_db_connection(c0)++ old_pool = db_handler.connection_pool+ old_pool.closeall()+ assert old_pool.closed++ conn = db_handler.get_db_connection()+ try:+ assert db_handler.connection_pool is not old_pool+ assert not db_handler.connection_pool.closed+ with conn.cursor() as cur:+ cur.execute("SELECT 1")+ assert cur.fetchone()[0] == 1+ conn.rollback()+ finally:+ db_handler.release_db_connection(conn)+++def test_token_required_releases_auth_conn_and_handles_route_errors(+ app, user_factory):+ user = user_factory()+ observed_checked_out = []++ probe = Flask(__name__)+ probe.config["SECRET_KEY"] = app.config["SECRET_KEY"]+ probe.config["JWT_EXPIRATION_DELTA"] = app.config["JWT_EXPIRATION_DELTA"]++ @probe.route("/probe/ok")+ @auth_utils.token_required+ def _ok():+ observed_checked_out.append(len(db_handler._checked_out))+ return jsonify({"ok": True}), 200++ @probe.route("/probe/boom")+ @auth_utils.token_required+ def _boom():+ raise RuntimeError("unexpected route failure")++ @probe.route("/probe/http-error")+ @auth_utils.token_required+ def _http_err():+ abort(413)++ probe_client = probe.test_client()++ # Auth connection must already be released before the route body runs.+ r_ok = probe_client.get("/probe/ok", headers=user["headers"])+ assert r_ok.status_code == 200+ assert observed_checked_out == [0]++ # Unhandled route exceptions keep returning a JSON 500, not HTML.+ r_boom = probe_client.get("/probe/boom", headers=user["headers"])+ assert r_boom.status_code == 500+ assert r_boom.is_json+ assert "message" in r_boom.get_json()++ # HTTPException (such as 413) propagates instead of becoming a 500.+ r_http = probe_client.get("/probe/http-error", headers=user["headers"])+ assert r_http.status_code == 413diff --git a/tests/test_photo_url.py b/tests/test_photo_url.pyindex 3ffbc75..8bf7827 100644--- a/tests/test_photo_url.py+++ b/tests/test_photo_url.py@@ -263,3 +263,29 @@ def test_photo_fetch_timeout_env_var(monkeypatch):probe_app.config["TESTING"] = TrueConfig.init_app(probe_app)assert probe_app.config["PHOTO_FETCH_TIMEOUT_SECONDS"] == 12.0+++def test_photo_fetch_timeout_env_var_enforced_end_to_end(monkeypatch):+ import time+ from flask import Flask+ from backend.config import Config+ from backend.warranties_routes import download_product_photo++ monkeypatch.setenv("PHOTO_FETCH_TIMEOUT_SECONDS", "1")+ probe_app = Flask(__name__)+ probe_app.config["TESTING"] = True+ Config.init_app(probe_app)+ probe_app.config["ALLOW_PRIVATE_PHOTO_URLS"] = True++ server = ThreadingHTTPServer(("127.0.0.1", 0), _DripHandler)+ thread = threading.Thread(target=server.serve_forever, daemon=True)+ thread.start()+ try:+ url = f"http://127.0.0.1:{server.server_address[1]}/drip.png"+ start = time.monotonic()+ with probe_app.app_context():+ with pytest.raises(ValueError, match="Timed out"):+ download_product_photo(url)+ assert time.monotonic() - start < 10+ finally:+ server.shutdown()diff --git a/tests/test_statistics.py b/tests/test_statistics.pyindex ef09fb5..8a704b3 100644--- a/tests/test_statistics.py+++ b/tests/test_statistics.py@@ -62,3 +62,27 @@ def test_total_value_currency_rules(client, user_factory, warranty_factory,st = _stats(client, h)assert st["total_value"] == 250 # 100 (no currency) + 150 (NULL), not 500+++def test_statistics_payloads_include_owner_user_id(+ client, user_factory, warranty_factory):+ alice = user_factory()+ bob = user_factory()++ w_alice = warranty_factory(alice["headers"], product_name="Alice Item").get_json()["id"]+ w_bob = warranty_factory(bob["headers"], product_name="Bob Item").get_json()["id"]++ me_alice = client.get("/api/auth/user", headers=alice["headers"]).get_json()+ me_bob = client.get("/api/auth/user", headers=bob["headers"]).get_json()+ alice_id = me_alice["user"]["id"] if "user" in me_alice else me_alice["id"]+ bob_id = me_bob["user"]["id"] if "user" in me_bob else me_bob["id"]++ personal = _stats(client, alice["headers"])+ by_id = {w["id"]: w for w in personal["all_warranties"]}+ assert by_id[w_alice]["user_id"] == alice_id++ r_global = client.get("/api/statistics/global", headers=bob["headers"])+ assert r_global.status_code == 200, r_global.get_data(as_text=True)+ global_by_id = {w["id"]: w for w in r_global.get_json()["all_warranties"]}+ assert global_by_id[w_alice]["user_id"] == alice_id+ assert global_by_id[w_bob]["user_id"] == bob_iddiff --git a/tests/test_status_edit_and_notes.py b/tests/test_status_edit_and_notes.pyindex 836ae46..57da8ee 100644--- a/tests/test_status_edit_and_notes.py+++ b/tests/test_status_edit_and_notes.py@@ -38,3 +38,31 @@ def test_notes_modal_disables_edit_notes_for_non_owners():notes = (REPO / "frontend" / "js" / "components" / "notes.js").read_text()assert "refs.editBtn.disabled = !canEdit" in notesassert "refs.editBtn.title = 'View only - not your warranty'" in notes+ assert "refs.editWarrantyBtn.disabled = !canEdit" in notes+ assert "refs.editWarrantyBtn.title = 'View only - not your warranty'" in notes+++def test_status_page_disables_edit_button_for_non_owners():+ status_js = (REPO / "frontend" / "status.js").read_text()+ assert "function canEditWarranty(warrantyUserId)" in status_js+ assert "user_id: warranty.user_id" in status_js+ assert 'disabled title="View only - not your warranty"' in status_js+++def test_total_value_card_has_z_index_above_charts():+ css = (REPO / "frontend" / "style.css").read_text()+ selector = '.status-card[data-status="total_value"] {'+ assert selector in css+ idx = css.index(selector)+ block = css[idx:css.index("}", idx) + 1]+ assert "z-index:" in block+++def test_warranty_list_stops_after_logout_before_second_fetch():+ controller = (+ REPO / "frontend" / "js" / "controllers" / "warrantyListController.js"+ ).read_text()+ first_fetch = controller.index("const primary = await listWarranties(")+ archived_fetch = controller.index("listWarranties({ scope, archived: true })")+ between = controller[first_fetch:archived_fetch]+ assert "if (!authService.isAuthenticated())" in between