fix(CR-02): prevent TOCTOU duplicate Zoom meetings on concurrent payment

- Add payment_processing status and atomic claim/release helpers in app/db.py

- Claim appointment atomically in pay_appointment, returning 409 on in-flight conflict and releasing claim on failure

- Add deterministic concurrency test in tests/test_app.py proving create_meeting runs only once
This commit is contained in:
kiskaadee committed 2026-11-21 17:15:14 -05:00
1 parent 37ef401bf7
commit 8c0191e958
4 files changed
+126 -17

No files matched your search

+27 -15
View File
@@ -133,22 +133,34 @@ def create_app(test_config: dict | None = None) -> Flask:
# Idempotent: return existing confirmed session without creating a duplicate meeting
if row["status"] == "confirmed":
return jsonify(AppointmentResponse.model_validate(row).model_dump()), 200
if row["status"] == "payment_processing":
return jsonify({"error": "El pago ya está siendo procesado."}), 409
token = zoom.get_access_token(body.credentials)
meeting = zoom.create_meeting(
access_token=token,
topic=f"Sesión con {row['client_name']}",
start_time_local=row["start_time_local"],
tz_name=row["timezone"],
duration_minutes=row["duration_minutes"],
)
updated = db.mark_appointment_confirmed(
session_id=row["session_id"],
zoom_meeting_id=str(meeting["id"]),
zoom_join_url=meeting["join_url"],
zoom_start_url=meeting["start_url"],
db_path=db_path,
)
if not db.claim_appointment_for_payment(row["session_id"], db_path=db_path):
latest = db.get_appointment_by_lookup(row["session_id"], db_path=db_path)
if latest and latest["status"] == "confirmed":
return jsonify(AppointmentResponse.model_validate(latest).model_dump()), 200
return jsonify({"error": "El pago ya está siendo procesado."}), 409
try:
token = zoom.get_access_token(body.credentials)
meeting = zoom.create_meeting(
access_token=token,
topic=f"Sesión con {row['client_name']}",
start_time_local=row["start_time_local"],
tz_name=row["timezone"],
duration_minutes=row["duration_minutes"],
)
updated = db.mark_appointment_confirmed(
session_id=row["session_id"],
zoom_meeting_id=str(meeting["id"]),
zoom_join_url=meeting["join_url"],
zoom_start_url=meeting["start_url"],
db_path=db_path,
)
except Exception:
db.release_payment_claim(row["session_id"], db_path=db_path)
raise
return jsonify(AppointmentResponse.model_validate(updated).model_dump()), 200
@app.delete("/api/appointments/<lookup_id>")
+28 -1
View File
@@ -41,7 +41,7 @@ def init_db(db_path: Path | None = None) -> None:
timezone TEXT NOT NULL,
duration_minutes INTEGER NOT NULL DEFAULT 60,
amount_usd REAL NOT NULL,
status TEXT NOT NULL CHECK (status IN ('payment_pending', 'confirmed')),
status TEXT NOT NULL CHECK (status IN ('payment_pending', 'payment_processing', 'confirmed')),
zoom_meeting_id TEXT,
zoom_join_url TEXT,
zoom_start_url TEXT,
@@ -110,6 +110,33 @@ def get_appointment_by_lookup(lookup_id: str, db_path: Path | None = None) -> di
return _row_to_dict(row)
def claim_appointment_for_payment(session_id: str, db_path: Path | None = None) -> bool:
"""Atomically claim a payment_pending appointment for Zoom meeting provisioning."""
with get_connection(db_path) as conn:
cursor = conn.execute(
"""
UPDATE appointments
SET status = 'payment_processing'
WHERE session_id = ? AND status = 'payment_pending'
""",
(session_id,),
)
return cursor.rowcount == 1
def release_payment_claim(session_id: str, db_path: Path | None = None) -> None:
"""Revert an in-flight payment_processing claim back to payment_pending."""
with get_connection(db_path) as conn:
conn.execute(
"""
UPDATE appointments
SET status = 'payment_pending'
WHERE session_id = ? AND status = 'payment_processing'
""",
(session_id,),
)
def mark_appointment_confirmed(
session_id: str,
zoom_meeting_id: str,
+1 -1
View File
@@ -59,7 +59,7 @@ class AppointmentResponse(BaseModel):
timezone: str
duration_minutes: int = 60
amount_usd: float
status: Literal["payment_pending", "confirmed"]
status: Literal["payment_pending", "payment_processing", "confirmed"]
zoom_meeting_id: str | None = None
zoom_join_url: str | None = None
zoom_start_url: str | None = None
+70
View File
@@ -1,4 +1,5 @@
import sqlite3
import threading
from pathlib import Path
import pytest
@@ -484,3 +485,72 @@ def test_duration_minutes_persisted_and_forwarded_to_zoom(client, monkeypatch):
assert p_resp.get_json()["duration_minutes"] == 45
assert len(captured_payloads) == 1
assert captured_payloads[0]["duration"] == 45
def test_concurrent_pay_creates_only_one_zoom_meeting(tmp_path: Path, monkeypatch):
db_file = tmp_path / "concurrent_pay.db"
app = create_app({"TESTING": True, "DB_PATH": str(db_file), "RATELIMIT_ENABLED": False})
create_calls = []
in_create = threading.Event()
allow_create_finish = threading.Event()
def fake_post(url, **kwargs):
if url == "https://zoom.us/oauth/token":
return FakeResponse(200, {"access_token": "mock_token"})
if url == "https://api.zoom.us/v2/users/me/meetings":
create_calls.append(kwargs.get("json"))
in_create.set()
assert allow_create_finish.wait(timeout=2.0)
return FakeResponse(
201,
{
"id": 555666777,
"join_url": "https://zoom.us/j/555666777",
"start_url": "https://zoom.us/s/555666777?zak=abc",
},
)
raise AssertionError(f"Unexpected POST URL: {url}")
monkeypatch.setattr(zoom.requests, "post", fake_post)
monkeypatch.setattr(
zoom.requests,
"get",
lambda url, **kwargs: FakeResponse(200, {"meetings": []}),
)
with app.test_client() as tc:
c_resp = tc.post(
"/api/appointments",
json={
"credentials": SAMPLE_CREDS,
"client_name": "María Perez",
"start_time_local": "2026-11-25T15:00",
},
)
assert c_resp.status_code == 201
sid = c_resp.get_json()["session_id"]
statuses = []
def worker_1():
with app.test_client() as tc1:
r = tc1.post(f"/api/appointments/{sid}/pay", json={"credentials": SAMPLE_CREDS})
statuses.append(r.status_code)
def worker_2():
assert in_create.wait(timeout=2.0)
with app.test_client() as tc2:
r = tc2.post(f"/api/appointments/{sid}/pay", json={"credentials": SAMPLE_CREDS})
statuses.append(r.status_code)
allow_create_finish.set()
t1 = threading.Thread(target=worker_1)
t2 = threading.Thread(target=worker_2)
t1.start()
t2.start()
t1.join(timeout=3.0)
t2.join(timeout=3.0)
assert len(create_calls) == 1
assert sorted(statuses) == [200, 409]