From 0337496c1dc58612585f855ba4e5dd87ed6e043c Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Sat, 21 Nov 2026 17:11:51 -0500 Subject: [PATCH] fix(CR-10): harden Zoom API JSON parsing, pagination, and required-key validation - Add _parse_json_dict in app/zoom.py to raise ZoomAPIError(502) on ValueError or non-object JSON - Default None meeting duration to 60 minutes and paginate check_slot_availability via next_page_token - Validate id, join_url, and start_url presence in create_meeting - Add TDD tests in tests/test_app.py covering all four Zoom API edge cases --- app/zoom.py | 71 ++++++++++++++++-------- tests/test_app.py | 137 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 186 insertions(+), 22 deletions(-) diff --git a/app/zoom.py b/app/zoom.py index f3417e9..c1c93f6 100644 --- a/app/zoom.py +++ b/app/zoom.py @@ -25,6 +25,16 @@ def _extract_zoom_error(resp: requests.Response) -> str: return resp.text or f"Zoom API HTTP {resp.status_code}" +def _parse_json_dict(resp: requests.Response, context: str) -> dict: + try: + data = resp.json() + except ValueError as exc: + raise ZoomAPIError(502, f"Invalid JSON response from Zoom {context}") from exc + if not isinstance(data, dict): + raise ZoomAPIError(502, f"Unexpected non-object JSON response from Zoom {context}") + return data + + def get_access_token(creds: ZoomCredentials) -> str: """Exchange Server-to-Server OAuth credentials for a short-lived Bearer token.""" raw = f"{creds.client_id}:{creds.client_secret.get_secret_value()}".encode("utf-8") @@ -43,7 +53,8 @@ def get_access_token(creds: ZoomCredentials) -> str: if not resp.ok: raise ZoomAPIError(resp.status_code, _extract_zoom_error(resp)) - token = resp.json().get("access_token") + data = _parse_json_dict(resp, "OAuth") + token = data.get("access_token") if not token: raise ZoomAPIError(502, "Zoom OAuth response did not include an access_token") return token @@ -69,28 +80,40 @@ def check_slot_availability( req_start = (parsed if parsed.tzinfo else parsed.replace(tzinfo=local_tz)).astimezone(timezone.utc) req_end = req_start + timedelta(minutes=duration_minutes) - try: - resp = requests.get( - "https://api.zoom.us/v2/users/me/meetings", - headers={"Authorization": f"Bearer {access_token}"}, - params={"type": "upcoming", "page_size": 100}, - timeout=15, - ) - except requests.RequestException as exc: - raise ZoomAPIError(502, f"Network error contacting Zoom Meetings API: {exc}") from exc + next_page_token = "" + while True: + params: dict[str, object] = {"type": "upcoming", "page_size": 100} + if next_page_token: + params["next_page_token"] = next_page_token - if not resp.ok: - raise ZoomAPIError(resp.status_code, _extract_zoom_error(resp)) + try: + resp = requests.get( + "https://api.zoom.us/v2/users/me/meetings", + headers={"Authorization": f"Bearer {access_token}"}, + params=params, + timeout=15, + ) + except requests.RequestException as exc: + raise ZoomAPIError(502, f"Network error contacting Zoom Meetings API: {exc}") from exc - for meeting in resp.json().get("meetings", []): - raw_start = meeting.get("start_time") - if not raw_start: - continue - m_start = datetime.fromisoformat(raw_start.replace("Z", "+00:00")) - m_end = m_start + timedelta(minutes=meeting.get("duration", 60)) - if req_start < m_end and req_end > m_start: - topic = meeting.get("topic", "Reunión existente") - return False, f"Conflicto con '{topic}' ({raw_start})" + if not resp.ok: + raise ZoomAPIError(resp.status_code, _extract_zoom_error(resp)) + + data = _parse_json_dict(resp, "Meetings API") + for meeting in data.get("meetings", []): + raw_start = meeting.get("start_time") + if not raw_start: + continue + m_start = datetime.fromisoformat(raw_start.replace("Z", "+00:00")) + duration = meeting.get("duration") or 60 + m_end = m_start + timedelta(minutes=duration) + if req_start < m_end and req_end > m_start: + topic = meeting.get("topic", "Reunión existente") + return False, f"Conflicto con '{topic}' ({raw_start})" + + next_page_token = data.get("next_page_token") or "" + if not next_page_token: + break return True, None @@ -132,7 +155,11 @@ def create_meeting( if not resp.ok: raise ZoomAPIError(resp.status_code, _extract_zoom_error(resp)) - return resp.json() + data = _parse_json_dict(resp, "Create Meeting") + required = ("id", "join_url", "start_url") + if any(not data.get(key) for key in required): + raise ZoomAPIError(502, "Zoom Create Meeting response missing required meeting fields") + return data def delete_meeting(access_token: str, meeting_id: str) -> None: diff --git a/tests/test_app.py b/tests/test_app.py index 5d17c66..c511374 100644 --- a/tests/test_app.py +++ b/tests/test_app.py @@ -197,3 +197,140 @@ def test_rate_limiting_blocks_brute_force(tmp_path: Path, monkeypatch): for _ in range(12) ] assert 429 in statuses + + +def test_zoom_invalid_json_returns_502(client, monkeypatch): + test_client, _ = client + monkeypatch.setattr( + zoom.requests, + "post", + lambda url, **kwargs: FakeResponse(200, ValueError("Invalid JSON"), text="not json"), + ) + resp = test_client.post("/api/zoom/verify-credentials", json=SAMPLE_CREDS) + assert resp.status_code == 502 + + +def test_check_slot_availability_handles_none_duration(client, monkeypatch): + test_client, _ = client + monkeypatch.setattr( + zoom.requests, + "post", + lambda url, **kwargs: FakeResponse(200, {"access_token": "mock_token"}), + ) + monkeypatch.setattr( + zoom.requests, + "get", + lambda url, **kwargs: FakeResponse( + 200, + { + "meetings": [ + { + "topic": "Reunión sin duración", + "start_time": "2026-11-25T20:00:00Z", + "duration": None, + } + ] + }, + ), + ) + resp = test_client.post( + "/api/appointments", + json={ + "credentials": SAMPLE_CREDS, + "client_name": "María Perez", + "start_time_local": "2026-11-25T15:00", + }, + ) + assert resp.status_code == 409 + + +def test_check_slot_availability_paginates_via_next_page_token(client, monkeypatch): + test_client, _ = client + seen_params = [] + + monkeypatch.setattr( + zoom.requests, + "post", + lambda url, **kwargs: FakeResponse(200, {"access_token": "mock_token"}), + ) + + def fake_get(url, **kwargs): + params = kwargs.get("params", {}) + seen_params.append(dict(params)) + if not params.get("next_page_token"): + return FakeResponse( + 200, + { + "meetings": [ + { + "topic": "Página 1", + "start_time": "2026-11-24T10:00:00Z", + "duration": 60, + } + ], + "next_page_token": "tok_page_2", + }, + ) + return FakeResponse( + 200, + { + "meetings": [ + { + "topic": "Conflicto Página 2", + "start_time": "2026-11-25T20:00:00Z", + "duration": 60, + } + ], + "next_page_token": "", + }, + ) + + monkeypatch.setattr(zoom.requests, "get", fake_get) + + resp = test_client.post( + "/api/appointments", + json={ + "credentials": SAMPLE_CREDS, + "client_name": "María Perez", + "start_time_local": "2026-11-25T15:00", + }, + ) + assert resp.status_code == 409 + assert "Conflicto Página 2" in resp.get_json()["error"] + assert len(seen_params) == 2 + assert seen_params[1].get("next_page_token") == "tok_page_2" + + +def test_create_meeting_missing_required_keys_returns_502(client, monkeypatch): + test_client, _ = client + + 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": + return FakeResponse(201, {"id": 12345}) # missing join_url, start_url + 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": []}), + ) + + c_resp = test_client.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"] + + p_resp = test_client.post( + f"/api/appointments/{sid}/pay", + json={"credentials": SAMPLE_CREDS}, + ) + assert p_resp.status_code == 502