diff --git a/CHANGELOG.md b/CHANGELOG.md index 5c2cd9f..465ae28 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,31 @@ All notable changes to this package are documented here. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the project uses [Semantic Versioning](https://semver.org/). +## [0.5.2] - 2026-10-15 + +The public thesis API (`https://id.cabalspy.xyz/thesis/v1/...`) and its live socket +(`wss://id.cabalspy.xyz/thesis/v1/ws/{chain}/{mint}`) now require your instance's public +client_id on every call. It is shown in the dashboard next to the API key; it is not a secret +and not the API key. The Data API (`CabalSpyID`, API key) is unchanged. + +### Changed (breaking for the thesis client) + +- `ThesisClient` / `AsyncThesisClient` require `client_id`: + `ThesisClient(access_token=None, *, client_id="csid_...", scope=None, ...)`. Without it (or with + an empty string) the constructor raises `AuthenticationError` with `code == "client_id_required"`. +- Every call sends the header `X-CSID-Client-Id: `; `live()` adds `client_id=` + to the socket URL (`scope="instance"` keeps working with the same client_id). `post()` and + `reply()` always send `client_id` in the body. + +### Added + +- New server error codes, mapped to the existing exception classes: `client_id_required` and + `invalid_client` (401, `AuthenticationError`), `origin_not_allowed` (403, `PermissionError`), + `rate_limited` (429, `RateLimitError`, `retry_after` from Retry-After, 60 s). +- `ThesisLive` treats the close codes 4401 (`client_id_required` / `invalid_client`) and 4403 + (`origin_not_allowed`) as final (no reconnect) and backs off 60 s after 4429 (`rate_limited`). +- `CLIENT_ID_HEADER` constant. + ## [0.5.1] - 2026-10-15 ### Changed @@ -96,6 +121,7 @@ First release. `NotFoundError`, `RateLimitError`, `ServerError`, `APIConnectionError`, `InvalidResponseError`, `OAuthError`, `TokenVerificationError`, `WebhookVerificationError`. +[0.5.2]: https://github.com/CabalSpy/cabalspy-id-python/compare/v0.5.1...v0.5.2 [0.5.1]: https://github.com/CabalSpy/cabalspy-id-python/compare/v0.5.0...v0.5.1 [0.5.0]: https://github.com/CabalSpy/cabalspy-id-python/compare/v0.4.1...v0.5.0 [0.4.1]: https://github.com/CabalSpy/cabalspy-id-python/compare/v0.4.0...v0.4.1 diff --git a/README.md b/README.md index 51922ca..5527911 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ pip install "cabalspy-id[stream]" |---|---| | `CabalSpyIDAuth` / `AsyncCabalSpyIDAuth` | OpenID Connect for your server: PKCE, code exchange, refresh, revoke, userinfo, ID token verification (ES256 / JWKS) | | `CabalSpyID` / `AsyncCabalSpyID` | Data API client for `https://api-id.cabalspy.xyz/v1`, typed responses, pagination, live trade stream | -| `ThesisClient` / `AsyncThesisClient` | public token thesis API with a user's access token, plus `live()` updates | +| `ThesisClient` / `AsyncThesisClient` | public token thesis API with your public `client_id` and a user's access token, plus `live()` updates | | `verify_webhook` | Standard Webhooks signature verification | Sync and async, fully typed (`py.typed`, `TypedDict` responses). Python 3.10+. @@ -249,7 +249,9 @@ A thesis is a short opinion on a token (up to 1000 characters), optionally tagge Writing needs the scope **`thesis`** in your login (`scope=["openid", "profile", "thesis"]`). -**Scope of reads.** Theses are shared across platforms. Every read (`list_theses`, `thesis_summary`, `latest_theses`, `ThesisClient`, the widget, the live sockets) takes `scope`: `global` (default, every platform) or `instance` (only theses written on your instance). In the Data API your key decides the instance; the public API and widget need your `client_id`. +**Scope of reads.** Theses are shared across platforms. Every read (`list_theses`, `thesis_summary`, `latest_theses`, `ThesisClient`, the widget, the live sockets) takes `scope`: `global` (default, every platform) or `instance` (only theses written on your instance). In the Data API your key decides the instance; the public API and widget use your `client_id`. + +**Your public `client_id` is required** for the public thesis API (`ThesisClient`, `AsyncThesisClient`, `ThesisLive`) and the theses widget. It is your instance's client_id (`csid_...`), shown in the dashboard next to the API key. It is public, not a secret and **not the API key** (the API key must never reach a browser). The SDK sends it as the `X-CSID-Client-Id` header on every call to `https://id.cabalspy.xyz/thesis/v1/...` and as `client_id` on the live socket URL (`wss://id.cabalspy.xyz/thesis/v1/ws/{chain}/{mint}?client_id=...`). Without it `ThesisClient()` raises `AuthenticationError` with `code == "client_id_required"`. Browser calls must come from one of the instance's allowed origins or verified domains (instances in dev mode also allow `http://localhost:*`). The Data API (`CabalSpyID`, API key) is unchanged. ### Widget @@ -329,12 +331,13 @@ Also over the trade stream (Pro plan): `csid.stream(events=["theses"], blockchai ### Public thesis API: `ThesisClient` -`https://id.cabalspy.xyz/thesis/v1` needs no API key: reading is open, writing uses the user's access token (scope `thesis`). +`https://id.cabalspy.xyz/thesis/v1` needs no API key, only your public `client_id` (required): reading needs nothing else, writing uses the user's access token (scope `thesis`). ```python from cabalspy_id import ThesisClient -# client_id credits posts to your app; add scope="instance" to show only theses written on your platform +# client_id: your instance's PUBLIC client_id from the dashboard (not the API key); it also credits +# posts to your app. Add scope="instance" to show only theses written on your platform. with ThesisClient(access_token=result.tokens["access_token"], client_id="csid_...") as theses: page = theses.list("solana", mint, sort="top") # items, pagination, token, summary if theses.me("solana", mint)["can_post"]: @@ -345,12 +348,23 @@ with ThesisClient(access_token=result.tokens["access_token"], client_id="csid_.. Methods: `list`, `iterate`, `summary`, `get`, `replies`, `by_user`, `me`, `post`, `reply`, `react`, `report`, `delete`, `notifications`, `mark_notifications_read`, `appeal`, `live`, `set_access_token`. `AsyncThesisClient` has the same methods as coroutines. Live updates for one token (async): ```python -live = ThesisClient().live("solana", mint) # also takes scope=, client_id= +live = ThesisClient(client_id="csid_...").live("solana", mint) # ?client_id=... (also takes scope=) live.on("thesis", lambda t: print("new", t["body"])) # also: reply, reaction, removed await live.connect() await live.run_forever() ``` +client_id errors use the SDK's exception classes, so check `err.code` (docs: `https://docs.cabalspy.xyz/cabalspy-id/errors#`): + +| Code | HTTP | Live socket close | Exception | Meaning | +|---|---|---|---|---| +| `client_id_required` | 401 | 4401 | `AuthenticationError` | no client_id sent | +| `invalid_client` | 401 | 4401 | `AuthenticationError` | unknown or inactive client_id | +| `origin_not_allowed` | 403 | 4403 | `PermissionError` | the browser's Origin is not one of the instance's allowed origins / verified domains | +| `rate_limited` | 429 | 4429 | `RateLimitError` (`retry_after == 60`) | too many requests per client or per IP | + +`ThesisLive` does not reconnect after 4401 or 4403 (`run_forever()` raises the error); after 4429 it waits 60 s before reconnecting. + ## Live stream Every trade of your users the moment it is indexed, with the trader's profile (Pro plan and up). Async only, needs `pip install "cabalspy-id[stream]"`. diff --git a/cabalspy_id/__init__.py b/cabalspy_id/__init__.py index 64668a1..66cabfb 100644 --- a/cabalspy_id/__init__.py +++ b/cabalspy_id/__init__.py @@ -17,6 +17,7 @@ from ._client import AsyncCabalSpyID, CabalSpyID, Envelope from ._constants import ( CHAINS, + CLIENT_ID_HEADER, CURRENCY_BY_CHAIN, DEFAULT_BASE_URL, DEFAULT_ISSUER, @@ -205,6 +206,7 @@ def __getattr__(name: str) -> object: "THESIS_MAX_BODY", "DEFAULT_THESIS_URL", "DEFAULT_THESIS_WS_URL", + "CLIENT_ID_HEADER", "StreamTopic", "ThesisStance", "ThesisSort", diff --git a/cabalspy_id/_constants.py b/cabalspy_id/_constants.py index 9290c7a..218c144 100644 --- a/cabalspy_id/_constants.py +++ b/cabalspy_id/_constants.py @@ -4,7 +4,7 @@ from typing import Literal -SDK_VERSION = "0.5.1" +SDK_VERSION = "0.5.2" USER_AGENT = f"cabalspy-id-python/{SDK_VERSION}" DEFAULT_BASE_URL = "https://api-id.cabalspy.xyz/v1" @@ -66,3 +66,5 @@ DEFAULT_THESES_STREAM_URL = "wss://api-id.cabalspy.xyz/v1/theses/stream" DEFAULT_THESIS_URL = "https://id.cabalspy.xyz/thesis/v1" DEFAULT_THESIS_WS_URL = "wss://id.cabalspy.xyz/thesis/v1/ws" +#: Header that carries the instance's public client_id on every public thesis API call. +CLIENT_ID_HEADER = "X-CSID-Client-Id" diff --git a/cabalspy_id/_errors.py b/cabalspy_id/_errors.py index a761f6b..fa58b27 100644 --- a/cabalspy_id/_errors.py +++ b/cabalspy_id/_errors.py @@ -83,11 +83,12 @@ class BadRequestError(CabalSpyIDError): class AuthenticationError(CabalSpyIDError): - """401 — missing_api_key.""" + """401 — missing_api_key; public thesis API: client_id_required, invalid_client.""" class PermissionError_(CabalSpyIDError): - """403 — invalid_api_key, product_not_enabled, no_instance, scope_not_allowed.""" + """403 — invalid_api_key, product_not_enabled, no_instance, scope_not_allowed; + public thesis API: origin_not_allowed.""" class PlanUserLimitError(PermissionError_): @@ -105,7 +106,7 @@ class NotFoundError(CabalSpyIDError): class RateLimitError(CabalSpyIDError): - """429 — rate_limit_exceeded.""" + """429 — rate_limit_exceeded; public thesis API: rate_limited (Retry-After 60).""" def __init__(self, message: str, *, retry_after: float | None = None, **kwargs: Any) -> None: super().__init__(message, **kwargs) diff --git a/cabalspy_id/_thesis.py b/cabalspy_id/_thesis.py index d512e3c..cf733fa 100644 --- a/cabalspy_id/_thesis.py +++ b/cabalspy_id/_thesis.py @@ -1,18 +1,21 @@ """Public thesis API: https://id.cabalspy.xyz/thesis/v1 (no API key). -Reading needs nothing. Writing uses the signed-in user's CabalSpy ID access -token with the scope "thesis" (``result.tokens["access_token"]`` after login). +Every call carries your instance's PUBLIC client_id (``csid_...``, shown in the +dashboard next to the API key; not the API key): header ``X-CSID-Client-Id``, +and ``client_id`` on the websocket URL. Reading needs nothing else. Writing uses +the signed-in user's CabalSpy ID access token with the scope "thesis" +(``result.tokens["access_token"]`` after login). from cabalspy_id import ThesisClient - theses = ThesisClient(access_token=tokens["access_token"]) + theses = ThesisClient(tokens["access_token"], client_id="csid_...") page = theses.list("solana", mint, sort="top") if theses.me("solana", mint)["can_post"]: theses.post("solana", mint, body="Strong community, still early.", stance="bull") Live updates for one token (async, needs the ``stream`` extra): - live = AsyncThesisClient().live("solana", mint) + live = AsyncThesisClient(client_id="csid_...").live("solana", mint) live.on("thesis", print) await live.connect() await live.run_forever() @@ -34,6 +37,7 @@ from ._constants import ( CHAINS, + CLIENT_ID_HEADER, DEFAULT_THESIS_URL, DEFAULT_THESIS_WS_URL, THESIS_EMOJIS, @@ -54,10 +58,82 @@ InvalidResponseError, PermissionError_, RateLimit, + RateLimitError, error_from_status, ) -__all__ = ["ThesisClient", "AsyncThesisClient", "ThesisLive", "TokenThesesPage", "ThesisPage", "LIVE_EVENTS"] +__all__ = [ + "ThesisClient", + "AsyncThesisClient", + "ThesisLive", + "TokenThesesPage", + "ThesisPage", + "LIVE_EVENTS", + "WS_CLOSE_CLIENT", + "WS_CLOSE_ORIGIN", + "WS_CLOSE_RATE_LIMITED", + "thesis_close_error", +] + +#: Live socket close codes for the client_id checks (the close reason is the error code). +WS_CLOSE_CLIENT = 4401 # client_id_required / invalid_client: final +WS_CLOSE_ORIGIN = 4403 # origin_not_allowed: final +WS_CLOSE_RATE_LIMITED = 4429 # rate_limited: reconnect after 60 s +#: Seconds to wait after a 4429 close (the server's Retry-After). +RATE_LIMIT_BACKOFF = 60.0 + +_DOCS = "https://docs.cabalspy.xyz/cabalspy-id/errors#" + +_CLIENT_ID_REQUIRED = ( + "ThesisClient needs your instance's public client_id (csid_..., shown in the dashboard next to the " + 'API key): ThesisClient(client_id="csid_..."). It is not the API key; never put the API key in a browser.' +) + + +def _require_client_id(client_id: Any) -> str: + if not isinstance(client_id, str) or not client_id.strip(): + raise AuthenticationError( + _CLIENT_ID_REQUIRED, + code="client_id_required", + parameter="client_id", + docs=f"{_DOCS}client_id_required", + ) + return client_id.strip() + + +def thesis_close_error(code: int | None, reason: str | None = None) -> CabalSpyIDError | None: + """The error for a refusing close code of the public live socket, or None for an ordinary close.""" + if code == WS_CLOSE_CLIENT: + c = "invalid_client" if reason == "invalid_client" else "client_id_required" + msg = ( + "The live socket was refused (4401): unknown or inactive client_id" + if c == "invalid_client" + else "The live socket was refused (4401): your instance's public client_id is required" + ) + return AuthenticationError(msg, code=c, status=401, docs=f"{_DOCS}{c}") + if code == WS_CLOSE_ORIGIN: + return PermissionError_( + "The live socket was refused (4403): this origin is not one of the instance's allowed origins", + code="origin_not_allowed", + status=403, + docs=f"{_DOCS}origin_not_allowed", + ) + if code == WS_CLOSE_RATE_LIMITED: + return RateLimitError( + "The live socket was refused (4429): rate limited; reconnecting in 60 s", + code="rate_limited", + status=429, + docs=f"{_DOCS}rate_limited", + retry_after=RATE_LIMIT_BACKOFF, + ) + if code == 1008: + return PermissionError_( + "The live socket was refused (1008): invalid token address or too many sockets from this IP", + code="ws_refused", + status=403, + ) + return None + #: Events of the public live socket. LIVE_EVENTS = ("thesis", "reply", "reaction", "removed", "heartbeat", "open", "close", "error") @@ -114,17 +190,19 @@ def __init__( self, access_token: str | None = None, *, - scope: ThesisScope | None = None, client_id: str | None = None, + scope: ThesisScope | None = None, base_url: str = DEFAULT_THESIS_URL, ws_url: str = DEFAULT_THESIS_WS_URL, timeout: float = 15.0, ) -> None: + client_id = _require_client_id(client_id) _scope_query(scope, client_id) - #: global (default) or instance: only theses written on ``client_id``'s instance. + #: global (default) or instance: only theses written on your instance. self.scope = scope - #: Your instance's client_id: needed for scope="instance"; also credits posts to your app. - self.client_id = client_id + #: Required. Your instance's PUBLIC client_id (not the API key): sent as ``X-CSID-Client-Id`` + #: on every call and as ``client_id`` on the live socket; also credits posts to your app. + self.client_id: str = client_id self._access_token = access_token self.base_url = base_url.rstrip("/") self.ws_url = ws_url.rstrip("/") @@ -141,7 +219,7 @@ def _request_args(self, auth: str | None) -> dict[str, str]: status=401, code="sign_in_required", ) - headers = {"Accept": "application/json", "User-Agent": USER_AGENT} + headers = {"Accept": "application/json", "User-Agent": USER_AGENT, CLIENT_ID_HEADER: self.client_id} if auth and self._access_token: headers["Authorization"] = f"Bearer {self._access_token}" return headers @@ -154,11 +232,16 @@ def _parse(response: httpx.Response, label: str) -> dict[str, Any]: parsed = None if response.status_code >= 400 or (isinstance(parsed, dict) and parsed.get("success") is False): err = parsed.get("error") if isinstance(parsed, dict) else None + retry_after: float | None + try: + retry_after = float(response.headers["Retry-After"]) + except (KeyError, ValueError): + retry_after = None raise error_from_status( response.status_code, err if isinstance(err, dict) else None, RateLimit(), - None, + retry_after, f"HTTP {response.status_code} on {label}", ) if not isinstance(parsed, dict) or "data" not in parsed: @@ -204,7 +287,7 @@ def _scope(self, scope: str | None, client_id: str | None) -> dict[str, str]: return _scope_query(scope or self.scope, client_id or self.client_id) def _attributed(self, body: dict[str, Any]) -> dict[str, Any]: - return {**body, "client_id": self.client_id} if self.client_id else body + return {**body, "client_id": self.client_id} def live( self, @@ -217,11 +300,11 @@ def live( ) -> ThesisLive: """Live updates for one token over the public websocket (async): thesis, reply, reaction, removed. - With ``scope="instance"`` (and ``client_id``) only theses written on that instance. + The socket URL carries ``client_id``. With ``scope="instance"`` only theses written on your instance. """ path = _token_path(chain, mint).removeprefix("/tokens") - query = urlencode(self._scope(scope, client_id)) - return ThesisLive(f"{self.ws_url}{path}" + (f"?{query}" if query else ""), **kwargs) + query = urlencode({"client_id": self.client_id, **self._scope(scope, client_id)}) + return ThesisLive(f"{self.ws_url}{path}?{query}", **kwargs) class ThesisClient(_ThesisBase): @@ -555,7 +638,9 @@ async def appeal(self, notification_id: int, message: str) -> dict[str, Any]: class ThesisLive: """Public live socket for one token (async). Events: thesis, reply, reaction, removed, heartbeat, open, close, error. Reconnects after drops or missed - heartbeats; close code 1008 (invalid token, too many sockets) is final.""" + heartbeats. Close codes 1008 (invalid token, too many sockets), 4401 + (client_id missing or invalid) and 4403 (origin not allowed) are final; + after 4429 (rate limited) it waits 60 s before reconnecting.""" def __init__( self, @@ -666,18 +751,20 @@ async def _read(self, ws: Any) -> None: if self._ws is ws: self._ws = None await self._emit("close", info) - if info.get("code") == 1008: - self._final = PermissionError_( - "The live socket was refused (1008): invalid token address or too many sockets from this IP", - code="ws_refused", - status=403, - ) - await self._emit("error", self._final) + refusal = thesis_close_error(info.get("code"), info.get("reason")) + rate_limited = info.get("code") == WS_CLOSE_RATE_LIMITED + if refusal is not None: + if not rate_limited: + self._final = refusal + await self._emit("error", refusal) if self._closed or self._final or not self.reconnect: self._done.set() return + min_delay = RATE_LIMIT_BACKOFF if rate_limited else 0.0 while not self._closed: - delay = min(self.reconnect_delay * (2**self._attempt), self.max_reconnect_delay) + random.random() * 0.25 + backoff = min(self.reconnect_delay * (2**self._attempt), self.max_reconnect_delay) + delay = max(min_delay, backoff) + random.random() * 0.25 + min_delay = 0.0 self._attempt += 1 await asyncio.sleep(delay) if self._closed: diff --git a/cabalspy_id/thesis.py b/cabalspy_id/thesis.py index 2b7eebd..a9c3ba1 100644 --- a/cabalspy_id/thesis.py +++ b/cabalspy_id/thesis.py @@ -3,7 +3,8 @@ - ``CabalSpyID`` / ``AsyncCabalSpyID``: Data API thesis methods (``list_theses``, ``post_thesis`` in a user's name, ...) -- ``ThesisClient`` / ``AsyncThesisClient``: public thesis API with a user's access token, ``live()`` +- ``ThesisClient`` / ``AsyncThesisClient``: public thesis API (your public ``client_id`` required) + with a user's access token, ``live()`` - ``ThesesStream``: live theses for up to 200 tokens per connection (every plan) from cabalspy_id.thesis import CabalSpyID, ThesisClient @@ -16,6 +17,7 @@ import cabalspy_id as _root from cabalspy_id import ( CHAINS, + CLIENT_ID_HEADER, DEFAULT_THESES_STREAM_URL, DEFAULT_THESIS_URL, DEFAULT_THESIS_WS_URL, @@ -114,6 +116,7 @@ "MAX_THESES_STREAM_TOKENS", "DEFAULT_THESIS_URL", "DEFAULT_THESIS_WS_URL", + "CLIENT_ID_HEADER", "DEFAULT_THESES_STREAM_URL", "Chain", "ThesisScope", diff --git a/pyproject.toml b/pyproject.toml index 0bdc278..89ae5d7 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "cabalspy-id" -version = "0.5.1" +version = "0.5.2" description = "SocialFi API & SDK for CabalSpy ID — add a social layer to any app: login with X + verified wallets, live trades and PnL of your users, token theses, leaderboards and copy trading on Solana, BNB Chain, Base, Ethereum and Robinhood Chain." readme = "README.md" license = "MIT" diff --git a/tests/live/test_live.py b/tests/live/test_live.py index 8c98037..b9e315c 100644 --- a/tests/live/test_live.py +++ b/tests/live/test_live.py @@ -89,12 +89,14 @@ def enc(o: object) -> str: WSOL = "So11111111111111111111111111111111111111112" +#: Public client_id of the CabalSpy ID playground instance (not a secret). +PLAYGROUND_CLIENT_ID = "csid_a97b0c26eccf6f41d5e3a99b" def test_public_theses() -> None: from cabalspy_id import BadRequestError, ThesisClient - with ThesisClient() as tc: + with ThesisClient(client_id=PLAYGROUND_CLIENT_ID) as tc: page = tc.list("solana", WSOL, limit=2) assert isinstance(page.items, list) assert page.token["mint"] == WSOL @@ -102,7 +104,7 @@ def test_public_theses() -> None: assert tc.summary("solana", WSOL)["token"]["mint"] == WSOL with pytest.raises(BadRequestError): tc.summary("solana", "not-a-mint") - with ThesisClient("not-a-token") as tc, pytest.raises(AuthenticationError): + with ThesisClient("not-a-token", client_id=PLAYGROUND_CLIENT_ID) as tc, pytest.raises(AuthenticationError): tc.me("solana", WSOL) @@ -114,7 +116,7 @@ def test_data_api_theses_needs_a_key() -> None: async def test_public_live_socket_opens() -> None: from cabalspy_id import AsyncThesisClient - async with AsyncThesisClient() as tc: + async with AsyncThesisClient(client_id=PLAYGROUND_CLIENT_ID) as tc: live = tc.live("solana", WSOL, reconnect=False) await live.connect() assert live.connected @@ -135,12 +137,12 @@ async def test_theses_stream_refuses_an_invalid_key() -> None: def test_public_scope_global() -> None: from cabalspy_id import ThesisClient - with ThesisClient(scope="global") as tc: + with ThesisClient(client_id=PLAYGROUND_CLIENT_ID, scope="global") as tc: assert isinstance(tc.summary("solana", WSOL)["theses"], int) def test_notifications_need_a_valid_token() -> None: from cabalspy_id import ThesisClient - with ThesisClient("not-a-token") as tc, pytest.raises(AuthenticationError): + with ThesisClient("not-a-token", client_id=PLAYGROUND_CLIENT_ID) as tc, pytest.raises(AuthenticationError): tc.notifications() diff --git a/tests/test_notifications.py b/tests/test_notifications.py index d156d51..db742df 100644 --- a/tests/test_notifications.py +++ b/tests/test_notifications.py @@ -84,7 +84,7 @@ def public(r: httpx.Request) -> httpx.Response: def test_public_notifications() -> None: rec = Recorder(public) - tc = ThesisClient("at", http_client=rec.client()) + tc = ThesisClient("at", client_id="csid_app", http_client=rec.client()) assert tc.notifications()["items"][0]["kind"] == "post_hidden" tc.mark_notifications_read() tc.appeal(7, "Please look again, this was a real analysis.") @@ -100,11 +100,11 @@ def test_public_notifications() -> None: ] assert all(r.headers["authorization"] == "Bearer at" for r in rec.requests) with pytest.raises(AuthenticationError): - ThesisClient(http_client=rec.client()).notifications() + ThesisClient(client_id="csid_app", http_client=rec.client()).notifications() async def test_async_public_notifications() -> None: - async with AsyncThesisClient("at", http_client=Recorder(public).async_client()) as tc: + async with AsyncThesisClient("at", client_id="csid_app", http_client=Recorder(public).async_client()) as tc: assert (await tc.notifications())["unread"] == 1 assert (await tc.mark_notifications_read())["read"] is True assert (await tc.appeal(7, "Please look again."))["appealed"] is True diff --git a/tests/test_theses.py b/tests/test_theses.py index e2b6e53..c4e112a 100644 --- a/tests/test_theses.py +++ b/tests/test_theses.py @@ -19,9 +19,11 @@ NotFoundError, PermissionError, PlanUserLimitError, + RateLimitError, ServerError, ThesisClient, ) +from cabalspy_id.thesis import CLIENT_ID_HEADER from .conftest import Recorder, api_error, ok @@ -259,10 +261,11 @@ def public_handler(r: httpx.Request) -> httpx.Response: def test_public_client_reads_and_writes() -> None: rec = Recorder(public_handler) - tc = ThesisClient(http_client=rec.client()) + tc = ThesisClient(client_id="csid_app", http_client=rec.client()) page = tc.list("solana", MINT, sort="top") assert page.items[0]["id"] == "t1" and page.token["symbol"] == "SOL" and page.summary["bull"] == 1 assert "authorization" not in rec.requests[0].headers + assert rec.requests[0].headers["x-csid-client-id"] == "csid_app" with pytest.raises(AuthenticationError) as e: tc.post("solana", MINT, body="x") assert e.value.code == "sign_in_required" @@ -278,13 +281,69 @@ def test_public_client_reads_and_writes() -> None: (r.method, str(r.url).removeprefix(BASE), json.loads(r.content) if r.content else None) for r in writes ] == [ ("GET", f"/tokens/solana/{MINT}/me", None), - ("POST", f"/tokens/solana/{MINT}", {"body": "gm", "stance": "bear"}), - ("POST", "/items/t1/replies", {"body": "agree"}), + ("POST", f"/tokens/solana/{MINT}", {"body": "gm", "stance": "bear", "client_id": "csid_app"}), + ("POST", "/items/t1/replies", {"body": "agree", "client_id": "csid_app"}), ("POST", "/items/t1/reactions", {"emoji": "🚀", "on": True}), ("POST", "/items/t1/report", {"reason": "scam", "note": "rug"}), ("DELETE", "/items/t1", None), ] assert all(r.headers["authorization"] == "Bearer at-1" for r in writes) + assert all(r.headers[CLIENT_ID_HEADER] == "csid_app" for r in rec.requests) + + +@pytest.mark.parametrize("client_id", [None, "", " "]) +def test_public_client_requires_client_id(client_id: str | None) -> None: + for cls in (ThesisClient, AsyncThesisClient): + with pytest.raises(AuthenticationError) as e: + cls(client_id=client_id) + assert e.value.code == "client_id_required" + assert e.value.parameter == "client_id" + assert "public client_id" in e.value.message and "not the API key" in e.value.message + with pytest.raises(AuthenticationError): + ThesisClient("access-token") + assert ThesisClient(client_id=" csid_app ").client_id == "csid_app" + + +def test_public_client_sends_client_id_header_on_every_call() -> None: + def handler(r: httpx.Request) -> httpx.Response: + if r.url.path.endswith("/summary"): + return httpx.Response(200, json={"success": True, "data": {"theses": 0}}) + if r.url.path.endswith("/me/notifications"): + return httpx.Response(200, json={"success": True, "data": {"unread": 0, "items": []}}) + return httpx.Response(200, json={"success": True, "data": thesis()}) + + rec = Recorder(handler) + tc = ThesisClient(client_id="csid_app", http_client=rec.client()) + tc.summary("solana", MINT) + tc.get("t1") + tc.set_access_token("at") + tc.notifications() + assert CLIENT_ID_HEADER == "X-CSID-Client-Id" + assert [r.headers["x-csid-client-id"] for r in rec.requests] == ["csid_app"] * 3 + # global scope: the header carries it, not the query + assert [r.url.params.get("client_id") for r in rec.requests] == [None] * 3 + + +@pytest.mark.parametrize( + ("status", "code", "cls", "headers"), + [ + (401, "client_id_required", AuthenticationError, None), + (401, "invalid_client", AuthenticationError, None), + (403, "origin_not_allowed", PermissionError, None), + (429, "rate_limited", RateLimitError, {"Retry-After": "60"}), + ], +) +def test_public_client_maps_client_id_errors( + status: int, code: str, cls: type[Exception], headers: dict[str, str] | None +) -> None: + rec = Recorder(lambda _r: api_error(status, code, headers=headers)) + with pytest.raises(cls) as e: + ThesisClient(client_id="csid_app", http_client=rec.client()).get("t1") + err: Any = e.value + assert err.code == code and err.status == status + assert err.docs == f"https://docs.cabalspy.xyz/cabalspy-id/errors#{code}" + if status == 429: + assert err.retry_after == 60 def test_public_client_errors() -> None: @@ -295,7 +354,7 @@ def handler(r: httpx.Request) -> httpx.Response: ) return httpx.Response(401, json={"success": False, "error": {"code": "invalid_token", "message": "Expired"}}) - tc = ThesisClient("at", http_client=Recorder(handler).client()) + tc = ThesisClient("at", client_id="csid_app", http_client=Recorder(handler).client()) with pytest.raises(PermissionError) as e: tc.post("solana", MINT, body="x") assert e.value.code == "not_a_holder" @@ -306,8 +365,10 @@ def handler(r: httpx.Request) -> httpx.Response: async def test_async_public_client() -> None: - async with AsyncThesisClient(http_client=Recorder(public_handler).async_client()) as tc: + rec = Recorder(public_handler) + async with AsyncThesisClient(client_id="csid_app", http_client=rec.async_client()) as tc: assert [t["id"] async for t in tc.iterate("solana", MINT)] == ["t1"] + assert rec.requests[0].headers["x-csid-client-id"] == "csid_app" # ── live: stream theses and the public socket ──────────────────────────────── @@ -322,6 +383,10 @@ async def handler(ws: Any) -> None: if state["mode"] == "refuse": await ws.close(code=1008) return + if state["mode"] == "close": + code, reason = state["close"] + await ws.close(code=code, reason=reason) + return if state["mode"] == "stream": q = {k: v[0] for k, v in parse_qs(urlsplit(ws.request.path).query).items()} await ws.send( @@ -419,7 +484,7 @@ def test_stream_validation() -> None: async def test_public_live(ws_server: dict[str, Any]) -> None: ws_server["mode"] = "public" - tc = ThesisClient(ws_url=f"ws://127.0.0.1:{ws_server['port']}/thesis/v1/ws") + tc = ThesisClient(client_id="csid_app", ws_url=f"ws://127.0.0.1:{ws_server['port']}/thesis/v1/ws") live = tc.live("solana", MINT) got: list[str] = [] live.on("thesis", lambda t: got.append(t["id"])) @@ -427,7 +492,7 @@ async def test_public_live(ws_server: dict[str, Any]) -> None: live.on("removed", lambda r: got.append(f"x:{r['id']}")) live.on("heartbeat", lambda _h: got.append("hb")) await live.connect() - assert ws_server["paths"][0] == f"/thesis/v1/ws/solana/{MINT}" + assert ws_server["paths"][0] == f"/thesis/v1/ws/solana/{MINT}?client_id=csid_app" for _ in range(100): if len(got) == 4: break @@ -438,10 +503,68 @@ async def test_public_live(ws_server: dict[str, Any]) -> None: async def test_public_live_refused_is_final(ws_server: dict[str, Any]) -> None: ws_server["mode"] = "refuse" - live = ThesisClient(ws_url=f"ws://127.0.0.1:{ws_server['port']}/thesis/v1/ws").live( + live = ThesisClient(client_id="csid_app", ws_url=f"ws://127.0.0.1:{ws_server['port']}/thesis/v1/ws").live( "solana", MINT, reconnect_delay=0.01 ) await live.connect() with pytest.raises(PermissionError): await asyncio.wait_for(live.run_forever(), 3) assert len(ws_server["paths"]) == 1 + + +@pytest.mark.parametrize( + ("code", "reason", "cls", "expected"), + [ + (4401, "client_id_required", AuthenticationError, "client_id_required"), + (4401, "invalid_client", AuthenticationError, "invalid_client"), + (4403, "origin_not_allowed", PermissionError, "origin_not_allowed"), + ], +) +async def test_public_live_client_id_refusals_are_final( + ws_server: dict[str, Any], code: int, reason: str, cls: type[Exception], expected: str +) -> None: + ws_server["mode"] = "close" + ws_server["close"] = (code, reason) + live = ThesisClient(client_id="csid_app", ws_url=f"ws://127.0.0.1:{ws_server['port']}/thesis/v1/ws").live( + "solana", MINT, reconnect_delay=0.01 + ) + errors: list[Any] = [] + live.on("error", errors.append) + await live.connect() + with pytest.raises(cls) as e: + await asyncio.wait_for(live.run_forever(), 3) + assert getattr(e.value, "code", None) == expected + assert [getattr(x, "code", None) for x in errors] == [expected] + await asyncio.sleep(0.1) + assert len(ws_server["paths"]) == 1 # no reconnect + + +async def test_public_live_rate_limited_backs_off(ws_server: dict[str, Any], monkeypatch: pytest.MonkeyPatch) -> None: + from cabalspy_id import _thesis + + ws_server["mode"] = "close" + ws_server["close"] = (4429, "rate_limited") + sleeps: list[float] = [] + real_sleep = asyncio.sleep + + async def fake_sleep(delay: float) -> None: + sleeps.append(delay) + await real_sleep(0) + + monkeypatch.setattr(_thesis.asyncio, "sleep", fake_sleep) + live = ThesisClient(client_id="csid_app", ws_url=f"ws://127.0.0.1:{ws_server['port']}/thesis/v1/ws").live( + "solana", MINT, reconnect_delay=0.01 + ) + errors: list[Any] = [] + live.on("error", errors.append) + await live.connect() + for _ in range(200): + if len(ws_server["paths"]) >= 2: + break + await real_sleep(0.01) + await live.close() + assert isinstance(errors[0], RateLimitError) and errors[0].code == "rate_limited" + assert errors[0].retry_after == 60 + assert any(60 <= s < 61 for s in sleeps) # the back-off before reconnecting + assert len(ws_server["paths"]) >= 2 # reconnected after the back-off + assert all(p.endswith("?client_id=csid_app") for p in ws_server["paths"]) diff --git a/tests/test_theses_stream.py b/tests/test_theses_stream.py index 8bca424..9e33ca0 100644 --- a/tests/test_theses_stream.py +++ b/tests/test_theses_stream.py @@ -11,7 +11,7 @@ import pytest from websockets.asyncio.server import serve -from cabalspy_id import BadRequestError, CabalSpyID, PermissionError, ThesisClient +from cabalspy_id import AuthenticationError, BadRequestError, CabalSpyID, PermissionError, ThesisClient from .conftest import Recorder, ok @@ -213,7 +213,11 @@ def handler(r: httpx.Request) -> httpx.Response: assert qs == [{"scope": ["instance"], "client_id": ["csid_app"]}, {"scope": ["global"]}] assert json.loads(rec.requests[2].content) == {"body": "gm", "client_id": "csid_app"} assert json.loads(rec.requests[3].content) == {"body": "yes", "client_id": "csid_app"} - assert tc.live("solana", MINT).url.endswith(f"/ws/solana/{MINT}?scope=instance&client_id=csid_app") - assert ThesisClient().live("solana", MINT, scope="global").url.endswith("?scope=global") - with pytest.raises(BadRequestError): + assert tc.live("solana", MINT).url.endswith(f"/ws/solana/{MINT}?client_id=csid_app&scope=instance") + assert ( + ThesisClient(client_id="csid_app") + .live("solana", MINT, scope="global") + .url.endswith("?client_id=csid_app&scope=global") + ) + with pytest.raises(AuthenticationError): ThesisClient(scope="instance")