From 3c09583c4cc790159f45800428e57405487c6510 Mon Sep 17 00:00:00 2001 From: Alex Harrison Date: Sun, 22 Nov 2026 11:14:56 -0700 Subject: [PATCH 1/2] Fix lane-8 security findings and fill test gaps - Encode coach athlete/activity/webhook ids; reject . and .. segments - Normalize method, refuse absolute URLs, cap backoff and error text - Parse Retry-After HTTP-dates; handle null/non-object error bodies - Validate api_key, timeout and max_retries in constructor - Add coach route tests and 14 partner method request tests --- saturday/client.py | 42 +++++-- saturday/errors.py | 56 +++++++-- tests/test_contracts.py | 42 +++++++ tests/test_request.py | 256 +++++++++++++++++++++++++++++++++++++++- 4 files changed, 371 insertions(+), 25 deletions(-) diff --git a/saturday/client.py b/saturday/client.py index d421e0f..63c71a6 100644 --- a/saturday/client.py +++ b/saturday/client.py @@ -8,10 +8,11 @@ from __future__ import annotations +import math import re import time from typing import Any, Dict, List, Optional, Sequence, Union -from urllib.parse import quote +from urllib.parse import quote, urlparse import httpx @@ -96,7 +97,10 @@ def _retry_safe_on_server_error(method: str, path: str) -> bool: def _seg(value: str) -> str: """Encode one path segment.""" - return quote(str(value), safe="") + text = str(value) + if text in (".", ".."): + raise ValueError(f"Invalid path segment: {text!r}") + return quote(text, safe="") def _params(**values: Any) -> Optional[Dict[str, Any]]: @@ -135,6 +139,17 @@ def __init__( max_retries: int = DEFAULT_MAX_RETRIES, bearer_token: Optional[str] = None, ): + if not isinstance(api_key, str) or not api_key: + raise ValueError("api_key must be a non-empty string") + if any(ord(c) < 32 or ord(c) == 127 for c in api_key): + raise ValueError("api_key must not contain control characters") + if timeout is not None: + if isinstance(timeout, bool) or not isinstance(timeout, (int, float)): + raise ValueError("timeout must be a finite number above 0") + if not math.isfinite(float(timeout)) or float(timeout) <= 0: + raise ValueError("timeout must be a finite number above 0") + if isinstance(max_retries, bool) or not isinstance(max_retries, int) or max_retries < 0: + raise ValueError("max_retries must be an integer of 0 or more") self._api_key = api_key self._base_url = base_url.rstrip("/") self._timeout = DEFAULT_TIMEOUT if timeout is None else timeout @@ -192,6 +207,10 @@ def request( since the server may have done the write. Daily ceilings, blocks, waits over 30 seconds and every other 4xx raise at once. """ + method = method.upper() + parsed_path = urlparse(path) + if parsed_path.scheme or parsed_path.netloc: + raise ValueError("path must be a relative URL path, not an absolute URL") last_error: Optional[SaturdayError] = None for attempt in range(self._max_retries + 1): @@ -210,7 +229,8 @@ def request( try: error_body = response.json() except Exception: - error_body = {"error": {"type": "api_error", "code": "unknown", "message": response.text or f"HTTP {response.status_code}"}} + fallback_message = (response.text or f"HTTP {response.status_code}")[:200] + error_body = {"error": {"type": "api_error", "code": "unknown", "message": fallback_message}} error = SaturdayError.from_response(response.status_code, error_body, response.headers.get("Retry-After")) last_error = error @@ -221,7 +241,7 @@ def request( elif response.status_code >= 500 and _retry_safe_on_server_error(method, path): if error.retry_after is not None and error.retry_after > MAX_RETRY_WAIT_SECONDS: raise error - delay = error.retry_after if error.retry_after is not None else 2 ** attempt + delay = error.retry_after if error.retry_after is not None else min(2 ** attempt, MAX_RETRY_WAIT_SECONDS) else: raise error if attempt < self._max_retries: @@ -806,7 +826,7 @@ def fueling_rollup( """One athlete's in-window fueling rollup + concern summary (roster-confined).""" return self._client.request( "GET", - f"/v1/coach/athletes/{athlete_uid}/fueling-rollup", + f"/v1/coach/athletes/{_seg(athlete_uid)}/fueling-rollup", params=_coach_read_params(window, focus), ) @@ -823,7 +843,7 @@ def report( if refresh: params["refresh"] = "true" return self._client.request( - "GET", f"/v1/coach/athletes/{athlete_uid}/report", params=params or None + "GET", f"/v1/coach/athletes/{_seg(athlete_uid)}/report", params=params or None ) def report_pdf( @@ -833,13 +853,13 @@ def report_pdf( params = _coach_read_params(window, focus) or {} params["format"] = "pdf" return self._client.request( - "GET", f"/v1/coach/athletes/{athlete_uid}/report", params=params, raw=True + "GET", f"/v1/coach/athletes/{_seg(athlete_uid)}/report", params=params, raw=True ) def session_detail(self, athlete_uid: str, activity_id: str) -> Dict[str, Any]: """Drill into one session by activity id (planned-vs-actual + markers).""" return self._client.request( - "GET", f"/v1/coach/athletes/{athlete_uid}/sessions/{activity_id}" + "GET", f"/v1/coach/athletes/{_seg(athlete_uid)}/sessions/{_seg(activity_id)}" ) # --- Config: alert rules --- @@ -927,15 +947,15 @@ def register_webhook(self, url: str, *, events: Optional[List[str]] = None) -> D def delete_webhook(self, webhook_id: str) -> Dict[str, Any]: """Delete a webhook endpoint by id.""" - return self._client.request("DELETE", f"/v1/coach/webhooks/{webhook_id}") + return self._client.request("DELETE", f"/v1/coach/webhooks/{_seg(webhook_id)}") def disable_webhook(self, webhook_id: str) -> Dict[str, Any]: """Disable a webhook endpoint (stops delivery without deleting it).""" - return self._client.request("POST", f"/v1/coach/webhooks/{webhook_id}/disable") + return self._client.request("POST", f"/v1/coach/webhooks/{_seg(webhook_id)}/disable") def enable_webhook(self, webhook_id: str) -> Dict[str, Any]: """Re-enable a previously disabled webhook endpoint.""" - return self._client.request("POST", f"/v1/coach/webhooks/{webhook_id}/enable") + return self._client.request("POST", f"/v1/coach/webhooks/{_seg(webhook_id)}/enable") # --- Billing (read-only; the key must carry billing:read) --- diff --git a/saturday/errors.py b/saturday/errors.py index 7de542c..2e345b1 100644 --- a/saturday/errors.py +++ b/saturday/errors.py @@ -7,6 +7,7 @@ import re from datetime import datetime, timedelta, timezone +from email.utils import parsedate_to_datetime from typing import Any, Dict, Optional # The 429 codes that reset at UTC midnight. Nothing they refuse succeeds before then. @@ -51,26 +52,55 @@ def __init__( self.retry_after = retry_after @classmethod - def from_response(cls, status: int, error_body: Dict[str, Any], retry_after: Optional[str] = None) -> "SaturdayError": + def from_response(cls, status: int, error_body: Any, retry_after: Optional[str] = None) -> "SaturdayError": """The error subclass for an API error response.""" - detail = error_body.get("error", error_body) if isinstance(error_body, dict) else {} + if isinstance(error_body, dict): + raw_detail = error_body.get("error", error_body) + detail = raw_detail if isinstance(raw_detail, dict) else {} + else: + detail = {} + message = detail.get("message") + if not isinstance(message, str) or not message: + message = f"HTTP {status}" + error_type = detail.get("type") + if not isinstance(error_type, str) or not error_type: + error_type = "api_error" + code = detail.get("code") + if not isinstance(code, str) or not code: + code = "unknown" + param = detail.get("param") if isinstance(detail.get("param"), str) else None + request_id = detail.get("request_id") if isinstance(detail.get("request_id"), str) else None + athlete_id = detail.get("athlete_id") if isinstance(detail.get("athlete_id"), str) else None kwargs: Dict[str, Any] = { - "message": detail.get("message", f"HTTP {status}"), + "message": message, "status": status, - "error_type": detail.get("type", "api_error"), - "code": detail.get("code", "unknown"), - "param": detail.get("param"), - "request_id": detail.get("request_id"), - "athlete_id": detail.get("athlete_id"), + "error_type": error_type, + "code": code, + "param": param, + "request_id": request_id, + "athlete_id": athlete_id, } seconds: Optional[float] = None if retry_after is not None: - try: - seconds = max(0.0, float(retry_after)) - except ValueError: + stripped = retry_after.strip() if isinstance(retry_after, str) else retry_after + if stripped is None or stripped == "": seconds = None - if seconds is not None and seconds.is_integer(): - seconds = int(seconds) + else: + try: + seconds = max(0.0, float(stripped)) # type: ignore[arg-type] + except (ValueError, TypeError): + try: + parsed = parsedate_to_datetime(stripped) # type: ignore[arg-type] + if parsed is None: + seconds = None + else: + if parsed.tzinfo is None: + parsed = parsed.replace(tzinfo=timezone.utc) + seconds = max(0.0, (parsed - datetime.now(timezone.utc)).total_seconds()) + except Exception: + seconds = None + if seconds is not None and float(seconds).is_integer(): + seconds = int(seconds) if status in (400, 422): return ValidationError(**kwargs) if status == 401: diff --git a/tests/test_contracts.py b/tests/test_contracts.py index 854ff6d..3b84c6d 100644 --- a/tests/test_contracts.py +++ b/tests/test_contracts.py @@ -229,3 +229,45 @@ def test_shared_profile_carries_every_answer_and_unshared_carries_none(): for name in ("fueling_profile_off", "fueling_profile_not_linked"): assert "profile" not in FIXTURES[name] and "updated_at" not in FIXTURES[name] assert isinstance(FIXTURES[name]["message"], str) + + +@pytest.mark.parametrize("call, method, path, body", [ + (lambda c: c.nutrition.extract(image_base64="AA=="), + "POST", "/v1/nutrition/extract", {"image_base64": "AA=="}), + (lambda c: c.infer.activity_type(activity_name="Morning Ride", tags=["bike"]), + "POST", "/v1/infer/activity-type", {"activity_name": "Morning Ride", "tags": ["bike"]}), + (lambda c: c.infer.brick_types(activity_name="Brick session"), + "POST", "/v1/infer/brick-types", {"activity_name": "Brick session"}), + (lambda c: c.integrations.disconnect("intervals_icu", "ath_1"), + "POST", "/v1/integrations/intervals_icu/disconnect", {"athlete_id": "ath_1"}), + (lambda c: c.organizations.update_subscription("org_1", "sub_1", seats=10), + "PATCH", "/v1/organizations/org_1/subscriptions/sub_1", {"seats": 10}), + (lambda c: c.organizations.add_licenses("org_1", "sub_1", [{"athlete_id": "ath_1"}]), + "POST", "/v1/organizations/org_1/subscriptions/sub_1/licenses", + {"licenses": [{"athlete_id": "ath_1"}]}), + (lambda c: c.organizations.list_licenses("org_1", "sub_1"), + "GET", "/v1/organizations/org_1/subscriptions/sub_1/licenses", None), + (lambda c: c.organizations.remove_license("org_1", "sub_1", "ath_1"), + "DELETE", "/v1/organizations/org_1/subscriptions/sub_1/licenses/ath_1", None), + (lambda c: c.knowledge.list_topics(), "GET", "/v1/knowledge/topics", None), + (lambda c: c.knowledge.get_article("art_1"), "GET", "/v1/knowledge/articles/art_1", None), + (lambda c: c.activities.get("ath_1", "act_1"), + "GET", "/v1/athletes/ath_1/activities/act_1", None), + (lambda c: c.organizations.get("org_1"), "GET", "/v1/organizations/org_1", None), + (lambda c: c.organizations.update("org_1", description="Weekend riders"), + "PATCH", "/v1/organizations/org_1", {"description": "Weekend riders"}), + (lambda c: c.organizations.get_offer("org_1"), "GET", "/v1/organizations/org_1/offer", None), +]) +def test_untested_methods_send_the_documented_request(call, method, path, body): + def send(request): + assert request.method == method + assert request.url.path == path + assert (json.loads(request.content) if request.content else None) == body + return httpx.Response(200, json={"ok": True}) + + client = Saturday(api_key="sk_test_fixture", max_retries=0) + client._client.close() + client._client = httpx.Client( + base_url=client._base_url, transport=httpx.MockTransport(send)) + with client: + call(client) diff --git a/tests/test_request.py b/tests/test_request.py index 7d56678..224697e 100644 --- a/tests/test_request.py +++ b/tests/test_request.py @@ -3,7 +3,7 @@ import httpx import pytest -from saturday import ConflictError, NotFoundError, PermissionDeniedError, RateLimitError, Saturday, ValidationError +from saturday import ConflictError, NotFoundError, PermissionDeniedError, RateLimitError, Saturday, SaturdayError, ValidationError @pytest.fixture @@ -301,3 +301,257 @@ def test_erase_incomplete_is_raised_not_retried(make_client): client.athletes.erase("ath_1") assert (raised.value.status, raised.value.code) == (503, "provider_erasure_incomplete") assert len(calls) == 1 + + +def test_coach_reads_and_config_writes_use_the_documented_routes(make_client): + seen = [] + + def handler(request): + seen.append(request) + return httpx.Response(200, json={"ok": True}) + + client = make_client(handler, max_retries=0) + client.coach.roster(window=7) + client.coach.roster_digest(window=14) + client.coach.fueling_rollup("ath_1", window=7, focus="worst") + client.coach.session_detail("ath_1", "act_1") + client.coach.get_notification_rules(scope="group", scope_id="grp_1") + client.coach.set_notification_rules("group", {"preset": "balanced"}, scope_id="grp_1") + client.coach.apply_preset(scope="overall", preset="balanced") + client.coach.get_report_settings(scope="athlete", scope_id="ath_1") + client.coach.set_report_settings("athlete", {"ai_report_window_days": 7}, scope_id="ath_1") + client.coach.list_webhooks() + client.coach.register_webhook("https://example.com/hook", events=["concern.detected"]) + client.coach.delete_webhook("cwh_1") + client.coach.disable_webhook("cwh_1") + client.coach.enable_webhook("cwh_1") + + calls = [ + (r.method, r.url.path, dict(r.url.params), json.loads(r.content) if r.content else None) + for r in seen + ] + assert calls == [ + ("GET", "/v1/coach/roster", {"window": "7"}, None), + ("GET", "/v1/coach/roster/digest", {"window": "14"}, None), + ("GET", "/v1/coach/athletes/ath_1/fueling-rollup", {"window": "7", "focus": "worst"}, None), + ("GET", "/v1/coach/athletes/ath_1/sessions/act_1", {}, None), + ("GET", "/v1/coach/config/notification-rules", {"scope": "group", "scope_id": "grp_1"}, None), + ("PUT", "/v1/coach/config/notification-rules", {}, + {"scope": "group", "scope_id": "grp_1", "rules": {"preset": "balanced"}}), + ("POST", "/v1/coach/config/preset", {}, + {"scope": "overall", "scope_id": None, "preset": "balanced"}), + ("GET", "/v1/coach/config/report-settings", {"scope": "athlete", "scope_id": "ath_1"}, None), + ("PUT", "/v1/coach/config/report-settings", {}, + {"scope": "athlete", "scope_id": "ath_1", "settings": {"ai_report_window_days": 7}}), + ("GET", "/v1/coach/webhooks", {}, None), + ("POST", "/v1/coach/webhooks", {}, + {"url": "https://example.com/hook", "events": ["concern.detected"]}), + ("DELETE", "/v1/coach/webhooks/cwh_1", {}, None), + ("POST", "/v1/coach/webhooks/cwh_1/disable", {}, None), + ("POST", "/v1/coach/webhooks/cwh_1/enable", {}, None), + ] + + +def test_coach_ids_are_segment_encoded(make_client): + seen = [] + + def handler(request): + seen.append(request.url.raw_path.decode()) + return httpx.Response(200, json={"ok": True}) + + client = make_client(handler, max_retries=0) + client.coach.fueling_rollup("../../partner") + client.coach.report("a/b?x=1") + client.coach.report_pdf("a/b") + client.coach.session_detail("x?admin=true", "a/b") + client.coach.delete_webhook("../billing/tier-status") + client.coach.disable_webhook("a/b") + client.coach.enable_webhook("a/b") + assert seen[0].startswith("/v1/coach/athletes/..%2F..%2Fpartner/fueling-rollup") + assert "/v1/coach/athletes/a%2Fb%3Fx%3D1/report" in seen[1] + assert "/v1/coach/athletes/a%2Fb/report" in seen[2] + assert "/v1/coach/athletes/x%3Fadmin%3Dtrue/sessions/a%2Fb" in seen[3] + assert seen[4] == "/v1/coach/webhooks/..%2Fbilling%2Ftier-status" + assert seen[5] == "/v1/coach/webhooks/a%2Fb/disable" + assert seen[6] == "/v1/coach/webhooks/a%2Fb/enable" + + +@pytest.mark.parametrize("bad", [".", ".."]) +def test_dot_path_segments_are_rejected(make_client, bad): + client = make_client(lambda _: httpx.Response(200, json={}), max_retries=0) + with pytest.raises(ValueError, match="Invalid path segment"): + client.athletes.get(bad) + with pytest.raises(ValueError, match="Invalid path segment"): + client.coach.fueling_rollup(bad) + with pytest.raises(ValueError, match="Invalid path segment"): + client.coach.delete_webhook(bad) + + +def test_lowercase_post_create_is_not_retried_on_5xx(make_client, monkeypatch): + monkeypatch.setattr("saturday.client.time.sleep", lambda _: None) + calls = [] + + def handler(request): + calls.append(request) + return httpx.Response(503, json={"error": {"message": "Try again"}}) + + client = make_client(handler, max_retries=3) + with pytest.raises(SaturdayError) as raised: + client.request("post", "/v1/athletes", json={"external_id": "u-1"}) + assert raised.value.status == 503 + assert len(calls) == 1 + assert calls[0].method == "POST" + + +def test_lowercase_safe_post_is_retried_on_5xx(make_client, monkeypatch): + monkeypatch.setattr("saturday.client.time.sleep", lambda _: None) + responses = iter([ + httpx.Response(503, json={"error": {"message": "Try again"}}), + httpx.Response(200, json={"ok": True}), + ]) + client = make_client(lambda _: next(responses), max_retries=1) + assert client.request("post", "/v1/nutrition/calculate", json={"activity_type": "run"}) == {"ok": True} + + +@pytest.mark.parametrize("bad_path", ["https://evil.invalid/steal", "http://evil.invalid/steal", "//evil.invalid/steal"]) +def test_absolute_urls_are_refused_in_request(make_client, bad_path): + called = [] + + def handler(request): + called.append(request) + return httpx.Response(200, json={}) + + client = make_client(handler, max_retries=0) + with pytest.raises(ValueError, match="relative URL"): + client.request("GET", bad_path) + assert called == [] + + +def test_retry_after_http_date_is_parsed(make_client): + from datetime import datetime, timedelta, timezone + from email.utils import formatdate + + future = datetime.now(timezone.utc) + timedelta(seconds=12) + header = formatdate(future.timestamp(), usegmt=True) + client = make_client( + lambda _: httpx.Response(429, json={"error": {"code": "rate_limit_exceeded", "message": "Slow"}}, headers={"Retry-After": header}), + max_retries=0, + ) + with pytest.raises(RateLimitError) as raised: + client.onboarding.questions() + assert raised.value.retry_after is not None + assert 9 <= raised.value.retry_after <= 13 + + +def test_retry_after_http_date_in_past_clamps_to_zero(make_client): + from datetime import datetime, timedelta, timezone + from email.utils import formatdate + + past = datetime.now(timezone.utc) - timedelta(seconds=30) + header = formatdate(past.timestamp(), usegmt=True) + client = make_client( + lambda _: httpx.Response(429, json={"error": {"code": "rate_limit_exceeded", "message": "Slow"}}, headers={"Retry-After": header}), + max_retries=0, + ) + with pytest.raises(RateLimitError) as raised: + client.onboarding.questions() + assert raised.value.retry_after == 0 + + +@pytest.mark.parametrize("header, expected", [("", None), (" ", None), ("not-a-date", None), ("-5", 0)]) +def test_retry_after_empty_and_invalid_are_absent(make_client, header, expected): + client = make_client( + lambda _: httpx.Response(429, json={"error": {"code": "rate_limit_exceeded", "message": "Slow"}}, headers={"Retry-After": header}), + max_retries=0, + ) + with pytest.raises(RateLimitError) as raised: + client.onboarding.questions() + assert raised.value.retry_after == expected + + +def test_retry_after_http_date_drives_503_wait(make_client, monkeypatch): + from datetime import datetime, timedelta, timezone + from email.utils import formatdate + + sleeps = [] + monkeypatch.setattr("saturday.client.time.sleep", sleeps.append) + future = datetime.now(timezone.utc) + timedelta(seconds=5) + header = formatdate(future.timestamp(), usegmt=True) + responses = iter([ + httpx.Response(503, json={"error": {"message": "Try again"}}, headers={"Retry-After": header}), + httpx.Response(200, json={"activity_types": [], "total": 0, "request_id": "r"}), + ]) + client = make_client(lambda _: next(responses)) + assert client.reference.activity_types()["total"] == 0 + assert len(sleeps) == 1 + assert 3 <= sleeps[0] <= 6 + + +@pytest.mark.parametrize("body", [b"null", b'"oops"', b"[1,2]", b"123"]) +def test_non_object_error_bodies_become_saturday_error(make_client, body): + client = make_client( + lambda _: httpx.Response(500, content=body, headers={"Content-Type": "application/json"}), + max_retries=0, + ) + with pytest.raises(SaturdayError) as raised: + client.onboarding.questions() + assert raised.value.status == 500 + assert raised.value.code == "unknown" + assert raised.value.message == "HTTP 500" + + +def test_nested_null_error_becomes_saturday_error(make_client): + client = make_client(lambda _: httpx.Response(500, json={"error": None}), max_retries=0) + with pytest.raises(SaturdayError) as raised: + client.onboarding.questions() + assert raised.value.status == 500 + assert raised.value.code == "unknown" + + +def test_nested_string_error_becomes_saturday_error(make_client): + client = make_client(lambda _: httpx.Response(404, json={"error": "missing"}), max_retries=0) + with pytest.raises(NotFoundError) as raised: + client.onboarding.questions() + assert raised.value.status == 404 + assert raised.value.code == "unknown" + + +def test_non_json_error_body_is_truncated(make_client): + big = ("x" * 5000).encode() + client = make_client(lambda _: httpx.Response(502, content=big), max_retries=0) + with pytest.raises(SaturdayError) as raised: + client.onboarding.questions() + assert raised.value.status == 502 + assert raised.value.code == "unknown" + assert len(raised.value.message) == 200 + + +@pytest.mark.parametrize("kwargs, option", [ + ({"api_key": ""}, "api_key"), + ({"api_key": "sk_test\r\nInjected: 1"}, "api_key"), + ({"api_key": "sk_test\x00bad"}, "api_key"), + ({"timeout": 0}, "timeout"), + ({"timeout": -5}, "timeout"), + ({"timeout": float("inf")}, "timeout"), + ({"timeout": float("nan")}, "timeout"), + ({"max_retries": -1}, "max_retries"), + ({"max_retries": 1.5}, "max_retries"), + ({"max_retries": "3"}, "max_retries"), +]) +def test_constructor_validates_options(kwargs, option): + if "api_key" in kwargs: + with pytest.raises(ValueError, match=option): + Saturday(**kwargs) + else: + with pytest.raises(ValueError, match=option): + Saturday(api_key="sk_test_fake", **kwargs) + + +def test_computed_backoff_is_capped_at_max_retry_wait(make_client, monkeypatch): + sleeps = [] + monkeypatch.setattr("saturday.client.time.sleep", sleeps.append) + client = make_client(lambda _: httpx.Response(503, json={"error": {"message": "Try again"}}), max_retries=7) + with pytest.raises(SaturdayError) as raised: + client.reference.activity_types() + assert raised.value.status == 503 + assert sleeps == [1, 2, 4, 8, 16, 30, 30] From 87a43a5017b1f6997979319ac79a534f087e84e3 Mon Sep 17 00:00:00 2001 From: Alex Harrison Date: Sun, 22 Nov 2026 11:27:03 -0700 Subject: [PATCH 2/2] Constructor check: an OAuth client may leave api_key empty when it passes bearer_token The new validation refused api_key="" even with a bearer token, which is how an OAuth-only partner constructs the client. Control characters are refused in whichever credential is sent. Co-Authored-By: Claude Opus 5.5 --- saturday/client.py | 7 ++++--- tests/test_request.py | 8 ++++++++ 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/saturday/client.py b/saturday/client.py index 63c71a6..885d774 100644 --- a/saturday/client.py +++ b/saturday/client.py @@ -139,10 +139,11 @@ def __init__( max_retries: int = DEFAULT_MAX_RETRIES, bearer_token: Optional[str] = None, ): - if not isinstance(api_key, str) or not api_key: + if not isinstance(api_key, str) or (not api_key and not bearer_token): raise ValueError("api_key must be a non-empty string") - if any(ord(c) < 32 or ord(c) == 127 for c in api_key): - raise ValueError("api_key must not contain control characters") + for name, value in (("api_key", api_key), ("bearer_token", bearer_token or "")): + if any(ord(c) < 32 or ord(c) == 127 for c in value): + raise ValueError(f"{name} must not contain control characters") if timeout is not None: if isinstance(timeout, bool) or not isinstance(timeout, (int, float)): raise ValueError("timeout must be a finite number above 0") diff --git a/tests/test_request.py b/tests/test_request.py index 224697e..53ac375 100644 --- a/tests/test_request.py +++ b/tests/test_request.py @@ -547,6 +547,14 @@ def test_constructor_validates_options(kwargs, option): Saturday(api_key="sk_test_fake", **kwargs) +def test_bearer_token_client_may_leave_api_key_empty(): + client = Saturday(api_key="", bearer_token="eyJ.test.token") + assert client._client.headers["Authorization"] == "Bearer eyJ.test.token" + client.close() + with pytest.raises(ValueError, match="bearer_token"): + Saturday(api_key="", bearer_token="eyJ\r\nX-Evil: 1") + + def test_computed_backoff_is_capped_at_max_retry_wait(make_client, monkeypatch): sleeps = [] monkeypatch.setattr("saturday.client.time.sleep", sleeps.append)