From ecd903acee13ca94ee029f2f607cb9532d4ca1f8 Mon Sep 17 00:00:00 2001 From: Sonny May Date: Sat, 14 Nov 2026 15:03:29 +0000 Subject: [PATCH] fix: reject malformed id path params with 422 instead of a retryable 503 Path ids for customers, devices, tickets, notes, history and RMAs were typed as plain strings, so a non-UUID value (stale link, typo, crafted input) was sent straight to Supabase. Postgres rejects it for a uuid column with a 400, which handle_response turns into a 503 "temporarily unavailable" with Retry-After: 30 - telling clients to retry a request that can never succeed. Typing these params as UUID makes FastAPI return 422 before any DB call, which also means crafted ids never reach a PostgREST filter. Tests now use real UUID fixtures, and the id-escaping tests assert the 422. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0171zWzo22EqdMY1jm7ohaqw --- backend/main.py | 42 ++++++++------- backend/test_main.py | 123 ++++++++++++++++++++++++------------------- 2 files changed, 92 insertions(+), 73 deletions(-) diff --git a/backend/main.py b/backend/main.py index a434e29..36fad9c 100644 --- a/backend/main.py +++ b/backend/main.py @@ -1,3 +1,5 @@ +from uuid import UUID + from fastapi import FastAPI, HTTPException, Query, Request, Response from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import JSONResponse @@ -141,13 +143,13 @@ def create_customer(c: Customer): @app.put("/customers/{id}") -def update_customer(id: str, c: Customer): - return db_patch("customers", id, model_data(c)) +def update_customer(id: UUID, c: Customer): + return db_patch("customers", str(id), model_data(c)) @app.delete("/customers/{id}") -def delete_customer(id: str): - return db_delete("customers", id) +def delete_customer(id: UUID): + return db_delete("customers", str(id)) # --- Devices --- @@ -162,8 +164,8 @@ def create_device(d: Device): @app.put("/devices/{id}") -def update_device(id: str, d: Device): - return db_patch("devices", id, clean_empty_strings(model_data(d), "customer_id")) +def update_device(id: UUID, d: Device): + return db_patch("devices", str(id), clean_empty_strings(model_data(d), "customer_id")) # --- Tickets --- @@ -216,8 +218,8 @@ def filter_tickets( @app.get("/tickets/{id}") -def get_ticket(id: str): - result = db_get("tickets", f"id=eq.{escape_filter_value(id)}") +def get_ticket(id: UUID): + result = db_get("tickets", f"id=eq.{escape_filter_value(str(id))}") if not result: raise HTTPException(status_code=404, detail="Ticket not found") return result[0] @@ -232,15 +234,15 @@ def create_ticket(t: Ticket): @app.put("/tickets/{id}") -def update_ticket(id: str, t: Ticket): +def update_ticket(id: UUID, t: Ticket): data = clean_empty_strings(model_data(t), "customer_id", "device_id", "assigned_user_id") - old = db_get("tickets", f"id=eq.{escape_filter_value(id)}&select=status") - result = db_patch("tickets", id, data) + old = db_get("tickets", f"id=eq.{escape_filter_value(str(id))}&select=status") + result = db_patch("tickets", str(id), data) if old and old[0]["status"] != data["status"]: db_post( "ticket_history", { - "ticket_id": id, + "ticket_id": str(id), "old_status": old[0]["status"], "new_status": data["status"], "changed_by": "Agent", @@ -251,8 +253,10 @@ def update_ticket(id: str, t: Ticket): # --- Notes --- @app.get("/tickets/{id}/notes") -def get_notes(id: str): - return db_get("ticket_notes", f"ticket_id=eq.{escape_filter_value(id)}&order=created_at.asc") +def get_notes(id: UUID): + return db_get( + "ticket_notes", f"ticket_id=eq.{escape_filter_value(str(id))}&order=created_at.asc" + ) @app.post("/notes") @@ -262,8 +266,10 @@ def create_note(n: TicketNote): # --- History --- @app.get("/tickets/{id}/history") -def get_history(id: str): - return db_get("ticket_history", f"ticket_id=eq.{escape_filter_value(id)}&order=changed_at.asc") +def get_history(id: UUID): + return db_get( + "ticket_history", f"ticket_id=eq.{escape_filter_value(str(id))}&order=changed_at.asc" + ) # --- RMAs --- @@ -278,8 +284,8 @@ def create_rma(r: RMA): @app.put("/rmas/{id}") -def update_rma(id: str, r: RMA): - return db_patch("rmas", id, model_data(r)) +def update_rma(id: UUID, r: RMA): + return db_patch("rmas", str(id), model_data(r)) # --- Dashboard --- diff --git a/backend/test_main.py b/backend/test_main.py index ebd5e80..20cb8e3 100644 --- a/backend/test_main.py +++ b/backend/test_main.py @@ -11,6 +11,12 @@ import pytest from fastapi.testclient import TestClient +CUSTOMER_ID = "00000000-0000-4000-8000-0000000000c1" +DEVICE_ID = "00000000-0000-4000-8000-0000000000d1" +TICKET_ID = "00000000-0000-4000-8000-0000000000a1" +RMA_ID = "00000000-0000-4000-8000-0000000000b1" +MISSING_ID = "00000000-0000-4000-8000-00000000ffff" + @pytest.fixture def client(monkeypatch): @@ -196,51 +202,50 @@ def fake_get(table, params=""): @pytest.mark.parametrize( - "path_template", - ["/tickets/{id}", "/tickets/{id}/notes", "/tickets/{id}/history"], + ("method", "path_template"), + [ + ("get", "/tickets/{id}"), + ("get", "/tickets/{id}/notes"), + ("get", "/tickets/{id}/history"), + ("put", "/tickets/{id}"), + ("put", "/customers/{id}"), + ("delete", "/customers/{id}"), + ("put", "/devices/{id}"), + ("put", "/rmas/{id}"), + ], ) -def test_ticket_id_routes_escape_postgrest_injection(client, monkeypatch, path_template): - test_client, main = client - captured = {} - - def fake_get(table, params=""): - captured["params"] = params - return [{"id": "t1"}] - - monkeypatch.setattr(main, "db_get", fake_get) - - # A crafted id that tries to append an extra filter / parameter. - payload = quote("t1&status=eq.Closed", safe="") - res = test_client.get(path_template.format(id=payload)) - - assert res.status_code == 200 - params = captured["params"] - assert "&status=eq.Closed" not in params - # Only the template's own "&order=" (if any) may remain. - assert params.count("&") <= 1, params - - -def test_update_ticket_escapes_id_in_status_lookup(client, monkeypatch): +@pytest.mark.parametrize( + "bad_id", + ["missing", "t1&status=eq.Closed", "not-a-uuid"], +) +def test_id_routes_reject_non_uuid_ids_before_querying( + client, monkeypatch, method, path_template, bad_id +): + """Malformed ids return 422 instead of reaching Supabase. + + Postgres rejects a non-UUID value for a uuid column with a 400, which + handle_response would surface as a misleading, retryable 503. Rejecting it + at the route also means crafted ids never reach a PostgREST filter. + """ test_client, main = client - captured = {} - def fake_get(table, params=""): - captured["get_params"] = params - return [{"status": "Open"}] + def fail(*_args, **_kwargs): + raise AssertionError("database should not be called for a malformed id") - monkeypatch.setattr(main, "db_get", fake_get) - monkeypatch.setattr(main, "db_patch", lambda table, id, data: [{"id": id, **data}]) - monkeypatch.setattr(main, "db_post", lambda table, data: [data]) + for name in ("db_get", "db_post", "db_patch", "db_delete"): + monkeypatch.setattr(main, name, fail) - payload = quote("t1&status=eq.Closed", safe="") - res = test_client.put( - f"/tickets/{payload}", - json={"title": "Printer", "status": "Open", "priority": "Low"}, - ) + bodies = { + "/tickets/{id}": {"title": "Printer", "status": "Open", "priority": "Low"}, + "/customers/{id}": {"name": "Acme"}, + "/devices/{id}": {"serial_number": "SN-1"}, + "/rmas/{id}": {"ticket_id": TICKET_ID, "rma_number": "RMA-1"}, + } + kwargs = {"json": bodies[path_template]} if method == "put" else {} + path = path_template.format(id=quote(bad_id, safe="")) + res = getattr(test_client, method)(path, **kwargs) - assert res.status_code == 200 - assert "&status=eq.Closed" not in captured["get_params"] - assert captured["get_params"].endswith("&select=status") + assert res.status_code == 422 def test_health_returns_ok(client): @@ -314,7 +319,7 @@ def test_data_route_returns_503_when_supabase_times_out(client, monkeypatch): def test_get_ticket_not_found_returns_404(client, monkeypatch): test_client, main = client monkeypatch.setattr(main, "db_get", lambda table, params="": []) - res = test_client.get("/tickets/missing") + res = test_client.get(f"/tickets/{MISSING_ID}") assert res.status_code == 404 assert res.json()["detail"] == "Ticket not found" @@ -346,8 +351,8 @@ def test_customer_crud_delegates_to_database(client, monkeypatch): ) create_res = test_client.post("/customers", json={"name": "Acme", "email": "ops@example.com"}) - update_res = test_client.put("/customers/c1", json={"name": "Acme Updated"}) - delete_res = test_client.delete("/customers/c1") + update_res = test_client.put(f"/customers/{CUSTOMER_ID}", json={"name": "Acme Updated"}) + delete_res = test_client.delete(f"/customers/{CUSTOMER_ID}") assert create_res.status_code == 200 assert update_res.status_code == 200 @@ -357,8 +362,8 @@ def test_customer_crud_delegates_to_database(client, monkeypatch): "customers", {"name": "Acme", "email": "ops@example.com", "phone": None, "company": None}, ) - assert calls[1][0:3] == ("patch", "customers", "c1") - assert calls[2] == ("delete", "customers", "c1") + assert calls[1][0:3] == ("patch", "customers", CUSTOMER_ID) + assert calls[2] == ("delete", "customers", CUSTOMER_ID) def test_device_routes_delegate_to_database(client, monkeypatch): @@ -377,14 +382,14 @@ def test_device_routes_delegate_to_database(client, monkeypatch): list_res = test_client.get("/devices") create_res = test_client.post("/devices", json={"serial_number": "SN-1", "model": "Router"}) - update_res = test_client.put("/devices/d1", json={"serial_number": "SN-2"}) + update_res = test_client.put(f"/devices/{DEVICE_ID}", json={"serial_number": "SN-2"}) assert list_res.status_code == 200 assert list_res.json() == rows assert create_res.status_code == 200 assert update_res.status_code == 200 assert calls[0][0:2] == ("post", "devices") - assert calls[1][0:3] == ("patch", "devices", "d1") + assert calls[1][0:3] == ("patch", "devices", DEVICE_ID) def test_device_routes_convert_blank_customer_id_to_null(client, monkeypatch): @@ -413,9 +418,9 @@ def test_ticket_routes_create_update_and_record_status_history(client, monkeypat posts = [] def fake_get(table, params=""): - if table == "tickets" and params.startswith("id=eq.t1&select=status"): + if table == "tickets" and params.startswith(f"id=eq.{TICKET_ID}&select=status"): return [{"status": "Open"}] - if table == "tickets" and params.startswith("id=eq.t1"): + if table == "tickets" and params.startswith(f"id=eq.{TICKET_ID}"): return [{"id": "t1", "status": "Open"}] return [{"id": "t1", "title": "Printer down"}] @@ -424,9 +429,11 @@ def fake_get(table, params=""): monkeypatch.setattr(main, "db_patch", lambda table, row_id, data: {"id": row_id, **data}) list_res = test_client.get("/tickets") - get_res = test_client.get("/tickets/t1") + get_res = test_client.get(f"/tickets/{TICKET_ID}") create_res = test_client.post("/tickets", json={"title": "Printer down", "status": "Open"}) - update_res = test_client.put("/tickets/t1", json={"title": "Printer fixed", "status": "Closed"}) + update_res = test_client.put( + f"/tickets/{TICKET_ID}", json={"title": "Printer fixed", "status": "Closed"} + ) assert list_res.status_code == 200 assert get_res.status_code == 200 @@ -434,7 +441,12 @@ def fake_get(table, params=""): assert update_res.status_code == 200 assert ( "ticket_history", - {"ticket_id": "t1", "old_status": "Open", "new_status": "Closed", "changed_by": "Agent"}, + { + "ticket_id": TICKET_ID, + "old_status": "Open", + "new_status": "Closed", + "changed_by": "Agent", + }, ) in posts @@ -467,9 +479,9 @@ def test_notes_and_history_routes_delegate_to_database(client, monkeypatch): ) monkeypatch.setattr(main, "db_post", lambda table, data: {"table": table, **data}) - notes_res = test_client.get("/tickets/t1/notes") + notes_res = test_client.get(f"/tickets/{TICKET_ID}/notes") create_note_res = test_client.post("/notes", json={"ticket_id": "t1", "note_text": "Rebooted"}) - history_res = test_client.get("/tickets/t1/history") + history_res = test_client.get(f"/tickets/{TICKET_ID}/history") assert notes_res.status_code == 200 assert notes_res.json()[0]["table"] == "ticket_notes" @@ -497,14 +509,15 @@ def test_rma_routes_delegate_to_database(client, monkeypatch): list_res = test_client.get("/rmas") create_res = test_client.post("/rmas", json={"ticket_id": "t1", "rma_number": "RMA-1"}) update_res = test_client.put( - "/rmas/r1", json={"ticket_id": "t1", "rma_number": "RMA-1", "resolution_status": "Shipped"} + f"/rmas/{RMA_ID}", + json={"ticket_id": "t1", "rma_number": "RMA-1", "resolution_status": "Shipped"}, ) assert list_res.status_code == 200 assert create_res.status_code == 200 assert update_res.status_code == 200 assert calls[0][0:2] == ("post", "rmas") - assert calls[1][0:3] == ("patch", "rmas", "r1") + assert calls[1][0:3] == ("patch", "rmas", RMA_ID) def test_dashboard_counts_ticket_and_rma_statuses(client, monkeypatch):