diff --git a/README.md b/README.md index 0efe664..16d804f 100644 --- a/README.md +++ b/README.md @@ -216,8 +216,8 @@ Constructor parameters for `SwgohComlink` and `SwgohComlinkAsync`: |-----------|------|---------|-------------| | `url` | `str` | `http://localhost:3000` | URL where swgoh-comlink is running | | `stats_url` | `str` | `http://localhost:3223` | URL where swgoh-stats service is running | -| `access_key` | `str` | `None` | HMAC public key. Also reads from `ACCESS_KEY` env var | -| `secret_key` | `str` | `None` | HMAC private key. Also reads from `SECRET_KEY` env var | +| `access_key` | `str` | `None` | HMAC public key. Also reads from `COMLINK_ACCESS_KEY` env var (`ACCESS_KEY` is deprecated) | +| `secret_key` | `str` | `None` | HMAC private key. Also reads from `COMLINK_SECRET_KEY` env var (`SECRET_KEY` is deprecated) | | `host` | `str` | `None` | Server hostname (overrides `url` and `stats_url`) | | `port` | `int` | `None` | Comlink TCP port. With `host` it defaults to `3000`; without `host` it replaces the port in `url` | | `stats_port` | `int` | `None` | Stats service TCP port. With `host` it defaults to `3223`; without `host` it replaces the port in `stats_url` | diff --git a/docs/api/async.md b/docs/api/async.md index e1d857f..d4c29a1 100644 --- a/docs/api/async.md +++ b/docs/api/async.md @@ -28,7 +28,7 @@ finally: `SwgohComlinkAsync` takes the same constructor arguments as the synchronous client: `url` or `host`/`port` to choose the service, and `access_key`/ -`secret_key` (or the `ACCESS_KEY`/`SECRET_KEY` environment variables) for HMAC +`secret_key` (or the `COMLINK_ACCESS_KEY`/`COMLINK_SECRET_KEY` environment variables) for HMAC signing. See [Connecting to Comlink](comlink.md#connecting-to-comlink). ```python @@ -41,6 +41,11 @@ async with SwgohComlinkAsync(host="192.168.1.10", port=3000) as comlink: Failed calls raise the same [typed HTTP errors](exceptions.md#http-errors) as the synchronous client. +## Limiting Response Size + +`max_response_bytes` and `max_game_data_bytes` work as in the synchronous +client; see [Limiting Response Size](comlink.md#limiting-response-size). + ## Retries and Pacing The `retry` argument takes the same [`RetryPolicy`](comlink.md#retries-and-pacing) diff --git a/docs/api/comlink.md b/docs/api/comlink.md index f9e2983..89bf633 100644 --- a/docs/api/comlink.md +++ b/docs/api/comlink.md @@ -39,8 +39,10 @@ When `host` is given, `url` and `stats_url` are ignored. If your comlink service requires HMAC signing, pass `access_key` and `secret_key`. When they are not passed, the client reads them from the -`ACCESS_KEY` and `SECRET_KEY` environment variables. Signing is turned on only -when both keys are set. +`COMLINK_ACCESS_KEY` and `COMLINK_SECRET_KEY` environment variables. Signing is +turned on only when both keys are set; if only one is set, the client logs a +warning. The old `ACCESS_KEY` and `SECRET_KEY` names still work but are +deprecated, and are read only when neither `COMLINK_*` name is set. See the [API Reference](#swgoh_comlink.swgoh_comlink.SwgohComlink) below for every constructor argument. @@ -52,6 +54,59 @@ When comlink answers with an HTTP error status, the client raises a `SwgohComlinkRateLimitError` for a rate refusal or `SwgohComlinkClientError` for a rejected request. All of them subclass `SwgohComlinkException`. +## Limiting Response Size + +By default the client reads each response in full, however large it is. On a +host with little memory, such as a Raspberry Pi, two keyword-only arguments +cap how much of a response body the client will read: + +- `max_response_bytes`: every endpoint except `/data`, including the stats + service used by `get_unit_stats`. +- `max_game_data_bytes`: `/data` only (`get_game_data`). It is separate + because game data is far larger than any other response, for the same reason + `/data` has its own, longer timeout. + +Both default to `None`, which means no limit. Limits count decoded bytes, +after any gzip decompression. When a limit is set: + +- A success response whose `Content-Length` is over the limit raises + `SwgohComlinkValueError` before any of the body is read. `Content-Length` is + the compressed size, so this check catches only bodies that are too large + even before decompression. +- Otherwise the client counts bytes as they arrive and raises + `SwgohComlinkValueError` as soon as the count passes the limit. This also + stops a small compressed body that would expand to a very large one. The + count is checked after each decoded chunk, so memory use can pass the limit + by up to one chunk. +- An HTTP error response is read up to the limit, and the body is cut there. + The [typed HTTP error](exceptions.md#http-errors) is raised as usual, so + `retry` still applies. + +`SwgohComlinkValueError` from a limit is never retried. Raise the limit, or set +it to `None`, for calls that need more. + +Measured decoded sizes in November 2026 (they grow with game updates, so leave +headroom): + +| Call | Size | +|------|------| +| `get_game_metadata()` | 43 KB | +| `get_player()` | 1.5 MB | +| `get_localization()` | 46 MB | +| `get_localization(unzip=True)` | 228 MB | +| `get_game_data(request_segment=1)` | 111 MB | +| `get_game_data()`, all collections | 405 MB | + +```python +from swgoh_comlink import SwgohComlink + +MiB = 1024 * 1024 +comlink = SwgohComlink(max_response_bytes=64 * MiB, max_game_data_bytes=512 * MiB) +``` + +With these values `get_localization(unzip=True)` fails; use `unzip=False` or a +larger `max_response_bytes` for it. + ## Retries and Pacing By default a client makes exactly one attempt per call and raises the diff --git a/docs/index.md b/docs/index.md index ca384fc..4e679b6 100644 --- a/docs/index.md +++ b/docs/index.md @@ -36,6 +36,12 @@ async with SwgohComlinkAsync(host="127.0.0.1", port=3000) as comlink: player = await comlink.get_player(allycode=245866537) ``` +If Comlink runs on another machine, reach it over `https` or a private network you trust, +such as a VPN or an SSH tunnel. HMAC signing (`access_key`/`secret_key`) proves who sent a +request, but over plain `http` it does not stop anyone on the network path from altering +responses or replaying signed requests. The client logs a warning when it signs requests sent +over plain `http` to a host other than `localhost`, `127.0.0.0/8` or `::1`; it still connects. + ## Choosing a Stats Method `SwgohComlink.get_unit_stats()` and `StatCalc.calc_player_stats()` are similar in outcome but different in execution model: diff --git a/docs/migration.md b/docs/migration.md index 2b23de1..949f303 100644 --- a/docs/migration.md +++ b/docs/migration.md @@ -308,6 +308,32 @@ added together. `ERA_DEFINITION`, `UBS_UPDATE`. New legacy-name aliases: `AbilityDecisionTrees`, `EraDefinitions`, `UBSUpdate`, `EpisodeDefinitions` (plural), `AccountLinking`. +## 10. v2.9 changes + +Upgrading from v2.8 to v2.9. + +- **`get_unit_stats(language=)` must be a language code.** A value that doesn't match + `xx_yy` / `xxx_yy` (letters only, e.g. `eng_us`) now raises `SwgohComlinkValueError` + instead of being passed through into the query string. A well-formed code that isn't in + `Constants.LANGUAGES` logs a warning and is still sent. Case is unchanged. +- **HMAC keys move to `COMLINK_ACCESS_KEY` / `COMLINK_SECRET_KEY`.** Rename the + `ACCESS_KEY` / `SECRET_KEY` environment variables. The old names still work until v3 + with a `DeprecationWarning`, and are read only when neither new name is set. + Constructor arguments still win. Setting only one key now logs a warning. +- **Plain-HTTP HMAC warning.** A client with HMAC keys whose `url` or `stats_url` is + `http://` to a non-loopback host logs one warning. Requests are still sent; switch to + `https` or a private network, or filter the `swgoh_comlink._base` logger. +- **Optional response size limits.** New keyword-only `max_response_bytes` and + `max_game_data_bytes` (for `/data`) arguments make the clients raise + `SwgohComlinkValueError` for a larger response, instead of reading it all into + memory. Both default to `None`, so nothing changes unless you set them. See + [Limiting Response Size](api/comlink.md#limiting-response-size). +- **`SwgohComlinkAsync` closes idle connections after 5 s.** It no longer keeps idle + pooled connections open forever; both clients now use the httpx default pool limits. + A new keyword-only `limits=httpx.Limits(...)` argument on both clients sets other + limits, e.g. `limits=httpx.Limits(keepalive_expiry=None)` restores the old async + behaviour. Request timeouts are unchanged. + ## Summary of changes | Area | Before (v1.x) | After | diff --git a/src/swgoh_comlink/_base.py b/src/swgoh_comlink/_base.py index 7beee1b..db6db1f 100644 --- a/src/swgoh_comlink/_base.py +++ b/src/swgoh_comlink/_base.py @@ -8,19 +8,31 @@ import functools import hashlib import hmac +import ipaddress +import logging import os +import re import time +import warnings from collections.abc import Callable from dataclasses import dataclass from json import dumps -from typing import Any, Self -from urllib.parse import urlparse, urlunparse +from typing import Any, Self, TypedDict +from urllib.parse import urlencode, urlparse, urlunparse + +import httpx from .exceptions import SwgohComlinkException, SwgohComlinkTypeError, SwgohComlinkValueError from .helpers import Constants, DataItems from .helpers._data_items import _items_wire_value from .retry import RetryPolicy, _no_release, _Pacer +logger = logging.getLogger(__name__) + +# A swgoh-stats language code such as ``eng_us``. Nothing that matches can carry ``&``, ``#``, ``=`` or ``/`` +# into the stats query string. +_LANGUAGE_CODE = re.compile(r"[A-Za-z]{2,3}_[A-Za-z]{2}") + __all__ = [ "SwgohComlinkBase", "param_alias", @@ -32,6 +44,11 @@ # Keys whose values must be masked in logs, repr, and debug output. _SENSITIVE_KEYS = frozenset({"secret_key", "access_key"}) +# Environment variables holding the HMAC (access, secret) key pair. The generic names are deprecated and are +# read only when neither namespaced name is set, so a pair is never assembled from both namespaces. +_CREDENTIAL_ENV_VARS = ("COMLINK_ACCESS_KEY", "COMLINK_SECRET_KEY") +_DEPRECATED_CREDENTIAL_ENV_VARS = ("ACCESS_KEY", "SECRET_KEY") + DEFAULT_TIMEOUT: float = 120.0 GAME_DATA_TIMEOUT: float = 300.0 DEFAULT_VERSION_CACHE_TTL: float = 3600.0 @@ -40,6 +57,12 @@ _now: Callable[[], float] = time.monotonic +class _PoolLimits(TypedDict, total=False): + """Connection pool keyword for ``httpx.Client`` / ``httpx.AsyncClient``; empty keeps the httpx defaults.""" + + limits: httpx.Limits + + @dataclass(frozen=True) class _CachedVersions: """Game data and localization bundle versions cached from a /metadata response. @@ -93,6 +116,55 @@ def sanitize_url(url: str) -> str: return url +def _is_plain_http_remote(url: str) -> bool: + """Whether *url* is plain ``http`` to a host other than ``localhost``, ``127.0.0.0/8`` or ``::1``.""" + parsed = urlparse(url) + if parsed.scheme.lower() != "http": + return False + host = (parsed.hostname or "").rstrip(".") + if host == "localhost": + return False + try: + return not ipaddress.ip_address(host).is_loopback + except ValueError: # a host name; resolving it would need a DNS lookup + return True + + +def _check_size_limit(name: str, value: int | None) -> int | None: + """Validate a response size limit argument: ``None`` or a positive ``int``.""" + if value is None: + return None + if not isinstance(value, int) or isinstance(value, bool): + raise SwgohComlinkTypeError(f"{name} must be an int or None, got {type(value).__name__}.") + if value <= 0: + raise SwgohComlinkValueError(f"{name} must be a positive number of bytes or None.") + return value + + +def _declared_length(headers: httpx.Headers) -> int | None: + """The ``Content-Length`` header as an ``int``, or ``None`` when absent or unreadable.""" + try: + return int(headers["content-length"]) + except (KeyError, ValueError): + return None + + +def _bounded_error_response(response: httpx.Response, body: bytes) -> httpx.Response: + """A copy of a streamed error *response* carrying *body*, its decoded and possibly cut-short content. + + The transfer headers are dropped because they described the encoded body, not *body*. + """ + headers = [ + (name, value) + for name, value in response.headers.multi_items() + if name.lower() not in ("content-encoding", "content-length", "transfer-encoding") + ] + extensions = {key: value for key, value in response.extensions.items() if key in ("http_version", "reason_phrase")} + return httpx.Response( + response.status_code, headers=headers, content=body, request=response.request, extensions=extensions + ) + + def _replace_port(url: str, port: int) -> str: """Return *url* with its port set to *port*, keeping its scheme and host.""" parsed = urlparse(url) @@ -153,6 +225,9 @@ def __init__( version_cache_ttl: float = DEFAULT_VERSION_CACHE_TTL, *, retry: RetryPolicy | None = None, + max_response_bytes: int | None = None, + max_game_data_bytes: int | None = None, + limits: httpx.Limits | None = None, ): from swgoh_comlink import version @@ -173,6 +248,14 @@ def __init__( raise SwgohComlinkTypeError(f"retry must be a RetryPolicy or None, got {type(retry).__name__}.") self.retry_policy = retry self._pacer = _Pacer(retry.min_interval, retry.unpaced_endpoints) if retry is not None else None + self.max_response_bytes = _check_size_limit("max_response_bytes", max_response_bytes) + self.max_game_data_bytes = _check_size_limit("max_game_data_bytes", max_game_data_bytes) + if limits is not None and not isinstance(limits, httpx.Limits): + raise SwgohComlinkTypeError(f"limits must be an httpx.Limits or None, got {type(limits).__name__}.") + self.limits = limits + # Both clients splat this into every httpx client they build, so their pools always match. + # Empty when limits is None, which leaves the httpx defaults (5 s idle keep-alive) in place. + self._pool_limits: _PoolLimits = {} if limits is None else {"limits": limits} # host replaces url and stats_url outright; port and stats_port alone replace only their ports if host: @@ -184,11 +267,64 @@ def __init__( if stats_port is not None: self.stats_url_base = _replace_port(self.stats_url_base, stats_port) - # Use values passed from client first, otherwise check for environment variables - self.access_key = access_key or os.environ.get("ACCESS_KEY") - self.secret_key = secret_key or os.environ.get("SECRET_KEY") + self.access_key, self.secret_key = self._resolve_credentials(access_key, secret_key) if self.access_key and self.secret_key: self.hmac = True + if plain := [url for url in (self.url_base, self.stats_url_base) if _is_plain_http_remote(url)]: + logger.warning( + "HMAC signing is on but %s uses plain HTTP to a non-loopback host. Signing does not protect " + "responses from being altered in transit or stop signed requests from being replayed; use " + "https or a private network.", + " and ".join(plain), + ) + elif self.access_key or self.secret_key: + present, missing = ("access_key", "secret_key") if self.access_key else ("secret_key", "access_key") + logger.warning( + "HMAC signing is off: %s is set but %s is not. Pass both keys, or set both %s and %s.", + present, + missing, + *_CREDENTIAL_ENV_VARS, + ) + + @staticmethod + def _resolve_credentials(access_key: str | None, secret_key: str | None) -> tuple[str | None, str | None]: + """Return the HMAC (access, secret) keys: constructor arguments first, then the environment. + + Emits one ``DeprecationWarning`` when a key is taken from ``ACCESS_KEY`` or ``SECRET_KEY``. + """ + env_names = _CREDENTIAL_ENV_VARS + env_values = [os.environ.get(name) or None for name in env_names] + if not any(env_values): + env_names = _DEPRECATED_CREDENTIAL_ENV_VARS + env_values = [os.environ.get(name) or None for name in env_names] + args = (access_key or None, secret_key or None) + if env_names is _DEPRECATED_CREDENTIAL_ENV_VARS and ( + used := [name for name, arg, value in zip(env_names, args, env_values, strict=True) if value and not arg] + ): + # stacklevel 4: this method, SwgohComlinkBase.__init__, the client's __init__, then the caller. + warnings.warn( + f"Reading HMAC keys from {' and '.join(used)} is deprecated and will be removed in v3. " + f"Set {' and '.join(_CREDENTIAL_ENV_VARS)} instead.", + DeprecationWarning, + stacklevel=4, + ) + access, secret = (arg or value for arg, value in zip(args, env_values, strict=True)) + return access, secret + + def _size_limit(self, endpoint: str, stats: bool) -> tuple[str, int | None]: + """The name and value of the response size limit for *endpoint*: ``/data`` has its own.""" + if endpoint == "data" and not stats: + return "max_game_data_bytes", self.max_game_data_bytes + return "max_response_bytes", self.max_response_bytes + + @staticmethod + def _too_large(endpoint: str, limit_name: str, limit: int, declared: int | None = None) -> SwgohComlinkValueError: + """The error for a response from *endpoint* larger than *limit* bytes.""" + size = f"declares {declared} bytes, over" if declared is not None else "is over" + return SwgohComlinkValueError( + f"Response from /{endpoint} {size} {limit_name} ({limit} bytes). " + f"Raise {limit_name}, or set it to None to remove the limit." + ) def _pace_delay(self, endpoint: str, stats: bool) -> float: """Reserve the next call slot for *endpoint* and return the seconds to wait for it. @@ -374,11 +510,15 @@ def _build_game_data_payload( def _build_unit_stats_endpoint(flags: list[str] | None = None, language: str | None = None) -> str: """Build the stats endpoint string with query parameters. + A well-formed ``language`` that is not in ``Constants.LANGUAGES`` logs a warning and is still sent, + so a language the game adds before the list is updated keeps working. + Returns: Endpoint string like ``"api?flags=calcGP&language=eng_us"``. Raises: - SwgohComlinkValueError: If flags contains invalid values. + SwgohComlinkValueError: If flags contains invalid values, or language is not a language code + such as ``eng_us``. """ _allowed_flags = { "gameStyle", @@ -394,23 +534,30 @@ def _build_unit_stats_endpoint(flags: list[str] | None = None, language: str | N "noSpace", } - flag_str = None + query: dict[str, str] = {} if flags: if isinstance(flags, list) and set(flags).issubset(_allowed_flags): - flag_str = "flags=" + ",".join(flags) + query["flags"] = ",".join(flags) else: raise SwgohComlinkValueError( f'Invalid argument. should be a list of strings with one or more of "' f"{_allowed_flags} flag values." ) - lang_str = f"language={language}" if language else None - - query_string = None - if flag_str or lang_str: - query_string = "?" + "&".join(filter(None, iter([flag_str, lang_str]))) + if language: + if not isinstance(language, str) or not _LANGUAGE_CODE.fullmatch(language): + raise SwgohComlinkValueError( + f"Invalid argument. should be a language code such as 'eng_us', got {language!r}." + ) + if language.lower() not in Constants.LANGUAGES: + logger.warning( + "Unknown language %r; sending it anyway. Known languages: %s", + language, + ", ".join(Constants.LANGUAGES), + ) + query["language"] = language - return "api" + query_string if query_string else "api" + return f"api?{urlencode(query, safe=',')}" if query else "api" @property def version(self) -> str: diff --git a/src/swgoh_comlink/swgoh_comlink.py b/src/swgoh_comlink/swgoh_comlink.py index f6a7332..f7bcdfe 100644 --- a/src/swgoh_comlink/swgoh_comlink.py +++ b/src/swgoh_comlink/swgoh_comlink.py @@ -17,7 +17,9 @@ DEFAULT_TIMEOUT, GAME_DATA_TIMEOUT, SwgohComlinkBase, + _bounded_error_response, _CachedVersions, + _declared_length, param_alias, ) from .exceptions import ( @@ -57,6 +59,14 @@ class SwgohComlink(SwgohComlinkBase): retry (RetryPolicy | None): Keyword-only. Retry rate refusals and HTTP 503 responses, and optionally space calls to the same endpoint, as described by a :class:`~swgoh_comlink.retry.RetryPolicy`. [Default: None, one attempt per call and no waiting] + max_response_bytes (int | None): Keyword-only. Largest response body, in decoded bytes, accepted from any + endpoint except /data. A larger response raises ``SwgohComlinkValueError``; an HTTP error body is cut + to this size. [Default: None, no limit] + max_game_data_bytes (int | None): Keyword-only. The same limit for /data (``get_game_data``), whose + responses are far larger than any other endpoint's. [Default: None, no limit] + limits (httpx.Limits | None): Keyword-only. Connection pool limits for both underlying httpx clients, + such as ``httpx.Limits(keepalive_expiry=30)``. Timeouts are not affected. + [Default: None, the httpx defaults: 100 connections, 20 kept alive, idle ones closed after 5 s] Notes: If the 'host' parameter is provided, the 'url' and 'stats_url' parameters are ignored. @@ -84,12 +94,14 @@ def __init__(self, **kwargs: Any) -> None: headers={"Content-Type": "application/json"}, verify=self.verify_ssl, timeout=DEFAULT_TIMEOUT, + **self._pool_limits, ) self.stats_client = httpx.Client( base_url=self.stats_url_base, headers={"Content-Type": "application/json"}, verify=self.verify_ssl, timeout=DEFAULT_TIMEOUT, + **self._pool_limits, ) def __enter__(self) -> SwgohComlink: @@ -191,10 +203,15 @@ def _send( if method.upper() != "GET": request_kwargs["content"] = body + limit_name, limit = self._size_limit(endpoint, stats) try: - r = client.request(method.upper(), f"/{endpoint}", **request_kwargs) - r.raise_for_status() - decoded = loads(r.content.decode("utf-8")) + if limit is None: + r = client.request(method.upper(), f"/{endpoint}", **request_kwargs) + r.raise_for_status() + content = r.content + else: + content = self._receive_limited(client, method, endpoint, request_kwargs, limit_name, limit) + decoded = loads(content.decode("utf-8")) if not isinstance(decoded, (dict, list)): raise SwgohComlinkDecodeError("Expected a JSON object or array in the service response.") return decoded @@ -205,6 +222,38 @@ def _send( except httpx.RequestError as e: raise SwgohComlinkException(e) from e + def _receive_limited( + self, + client: httpx.Client, + method: str, + endpoint: str, + request_kwargs: dict[str, Any], + limit_name: str, + limit: int, + ) -> bytes: + """Stream one response, reading at most *limit* decoded bytes of its body. + + A success larger than *limit* raises ``SwgohComlinkValueError``, before any of the body is read when + ``Content-Length`` already exceeds it. An error body is cut to *limit* bytes and raised through + ``raise_for_status``. + """ + with client.stream(method.upper(), f"/{endpoint}", **request_kwargs) as r: + if r.is_success and (declared := _declared_length(r.headers)) is not None and declared > limit: + raise self._too_large(endpoint, limit_name, limit, declared) + chunks: list[bytes] = [] + size = 0 + for chunk in r.iter_bytes(): + chunks.append(chunk) + size += len(chunk) + if size > limit: + if r.is_success: + raise self._too_large(endpoint, limit_name, limit) + break + body = b"".join(chunks) + if not r.is_success: + _bounded_error_response(r, body[:limit]).raise_for_status() + return body + def _post( self, endpoint: str = "", diff --git a/src/swgoh_comlink/swgoh_comlink_async.py b/src/swgoh_comlink/swgoh_comlink_async.py index 6e3193a..745c90b 100644 --- a/src/swgoh_comlink/swgoh_comlink_async.py +++ b/src/swgoh_comlink/swgoh_comlink_async.py @@ -17,7 +17,9 @@ DEFAULT_TIMEOUT, GAME_DATA_TIMEOUT, SwgohComlinkBase, + _bounded_error_response, _CachedVersions, + _declared_length, param_alias, ) from .exceptions import ( @@ -57,6 +59,14 @@ class SwgohComlinkAsync(SwgohComlinkBase): retry (RetryPolicy | None): Keyword-only. Retry rate refusals and HTTP 503 responses, and optionally space calls to the same endpoint, as described by a :class:`~swgoh_comlink.retry.RetryPolicy`. [Default: None, one attempt per call and no waiting] + max_response_bytes (int | None): Keyword-only. Largest response body, in decoded bytes, accepted from any + endpoint except /data. A larger response raises ``SwgohComlinkValueError``; an HTTP error body is cut + to this size. [Default: None, no limit] + max_game_data_bytes (int | None): Keyword-only. The same limit for /data (``get_game_data``), whose + responses are far larger than any other endpoint's. [Default: None, no limit] + limits (httpx.Limits | None): Keyword-only. Connection pool limits for both underlying httpx clients, + such as ``httpx.Limits(keepalive_expiry=30)``. Timeouts are not affected. + [Default: None, the httpx defaults: 100 connections, 20 kept alive, idle ones closed after 5 s] Notes: If the 'host' parameter is provided, the 'url' and 'stats_url' parameters are ignored. @@ -74,20 +84,19 @@ def __init__(self, **kwargs: Any) -> None: super().__init__(**kwargs) self._version_lock = asyncio.Lock() self._enums_lock = asyncio.Lock() - connection_limits = httpx.Limits(keepalive_expiry=None) self.client = httpx.AsyncClient( base_url=self.url_base, headers={"Content-Type": "application/json"}, verify=self.verify_ssl, timeout=DEFAULT_TIMEOUT, - limits=connection_limits, + **self._pool_limits, ) self.stats_client = httpx.AsyncClient( base_url=self.stats_url_base, headers={"Content-Type": "application/json"}, verify=self.verify_ssl, timeout=DEFAULT_TIMEOUT, - limits=connection_limits, + **self._pool_limits, ) async def __aenter__(self) -> SwgohComlinkAsync: @@ -189,10 +198,15 @@ async def _send( if method.upper() != "GET": request_kwargs["content"] = body + limit_name, limit = self._size_limit(endpoint, stats) try: - r = await client.request(method.upper(), f"/{endpoint}", **request_kwargs) - r.raise_for_status() - decoded = loads(r.content.decode("utf-8")) + if limit is None: + r = await client.request(method.upper(), f"/{endpoint}", **request_kwargs) + r.raise_for_status() + content = r.content + else: + content = await self._receive_limited(client, method, endpoint, request_kwargs, limit_name, limit) + decoded = loads(content.decode("utf-8")) if not isinstance(decoded, (dict, list)): raise SwgohComlinkDecodeError("Expected a JSON object or array in the service response.") return decoded @@ -203,6 +217,38 @@ async def _send( except httpx.RequestError as e: raise SwgohComlinkException(e) from e + async def _receive_limited( + self, + client: httpx.AsyncClient, + method: str, + endpoint: str, + request_kwargs: dict[str, Any], + limit_name: str, + limit: int, + ) -> bytes: + """Stream one response, reading at most *limit* decoded bytes of its body. + + A success larger than *limit* raises ``SwgohComlinkValueError``, before any of the body is read when + ``Content-Length`` already exceeds it. An error body is cut to *limit* bytes and raised through + ``raise_for_status``. + """ + async with client.stream(method.upper(), f"/{endpoint}", **request_kwargs) as r: + if r.is_success and (declared := _declared_length(r.headers)) is not None and declared > limit: + raise self._too_large(endpoint, limit_name, limit, declared) + chunks: list[bytes] = [] + size = 0 + async for chunk in r.aiter_bytes(): + chunks.append(chunk) + size += len(chunk) + if size > limit: + if r.is_success: + raise self._too_large(endpoint, limit_name, limit) + break + body = b"".join(chunks) + if not r.is_success: + _bounded_error_response(r, body[:limit]).raise_for_status() + return body + async def _post( self, endpoint: str = "", diff --git a/tests/unit/test_base.py b/tests/unit/test_base.py index 0f83b93..498a52d 100644 --- a/tests/unit/test_base.py +++ b/tests/unit/test_base.py @@ -162,8 +162,10 @@ def test_hmac_disabled_without_keys(self): client.close() def test_hmac_from_env(self, monkeypatch): - monkeypatch.setenv("ACCESS_KEY", "env_pub") - monkeypatch.setenv("SECRET_KEY", "env_priv") + monkeypatch.delenv("ACCESS_KEY", raising=False) + monkeypatch.delenv("SECRET_KEY", raising=False) + monkeypatch.setenv("COMLINK_ACCESS_KEY", "env_pub") + monkeypatch.setenv("COMLINK_SECRET_KEY", "env_priv") client = SwgohComlink() assert client.hmac is True assert client.access_key == "env_pub" diff --git a/tests/unit/test_connection_limits.py b/tests/unit/test_connection_limits.py new file mode 100644 index 0000000..034b6d1 --- /dev/null +++ b/tests/unit/test_connection_limits.py @@ -0,0 +1,95 @@ +"""Connection-pool ``limits`` parity between the sync and async clients.""" + +from __future__ import annotations + +import inspect +from typing import Any + +import httpx +import pytest + +from swgoh_comlink import SwgohComlink, SwgohComlinkAsync +from swgoh_comlink._base import DEFAULT_TIMEOUT, SwgohComlinkBase +from swgoh_comlink.exceptions import SwgohComlinkTypeError + +_MISSING = object() + + +def _record_client_kwargs(monkeypatch: pytest.MonkeyPatch) -> list[dict[str, Any]]: + """Patch both httpx client classes to record the keyword arguments each instance is built with.""" + calls: list[dict[str, Any]] = [] + + for cls in (httpx.Client, httpx.AsyncClient): + + def init(self: Any, *args: Any, _original: Any = cls.__init__, **kwargs: Any) -> None: + calls.append(kwargs) + _original(self, *args, **kwargs) + + monkeypatch.setattr(cls, "__init__", init) + return calls + + +def _limits_passed(calls: list[dict[str, Any]]) -> list[Any]: + return [kwargs.get("limits", _MISSING) for kwargs in calls] + + +def _pool(client: Any) -> Any: + """The httpcore connection pool behind an httpx client's default transport.""" + return client._transport._pool + + +@pytest.mark.parametrize( + "limits", + [None, httpx.Limits(max_connections=7, max_keepalive_connections=3, keepalive_expiry=30.0)], + ids=["default", "custom"], +) +def test_sync_and_async_pass_identical_limits_to_httpx(monkeypatch: pytest.MonkeyPatch, limits: Any) -> None: + calls = _record_client_kwargs(monkeypatch) + sync = SwgohComlink(limits=limits) + sync_limits = _limits_passed(calls) + calls.clear() + SwgohComlinkAsync(limits=limits) + async_limits = _limits_passed(calls) + + assert len(sync_limits) == len(async_limits) == 2 # client and stats_client + assert sync_limits == async_limits + expected = _MISSING if limits is None else limits + assert sync_limits == [expected, expected] + sync.close() + + +def test_default_keepalive_expiry_matches_httpx_default_in_both_clients() -> None: + reference = _pool(httpx.Client()) + sync = SwgohComlink() + async_client = SwgohComlinkAsync() + for pool in (_pool(c) for c in (sync.client, sync.stats_client, async_client.client, async_client.stats_client)): + assert pool._keepalive_expiry == reference._keepalive_expiry == 5.0 + assert pool._max_connections == reference._max_connections + assert pool._max_keepalive_connections == reference._max_keepalive_connections + sync.close() + + +@pytest.mark.parametrize("cls", [SwgohComlink, SwgohComlinkAsync]) +def test_custom_limits_reach_both_connection_pools(cls: type[SwgohComlink] | type[SwgohComlinkAsync]) -> None: + client = cls(limits=httpx.Limits(max_connections=7, max_keepalive_connections=3, keepalive_expiry=None)) + for pool in (_pool(client.client), _pool(client.stats_client)): + assert (pool._max_connections, pool._max_keepalive_connections, pool._keepalive_expiry) == (7, 3, None) + + +def test_limits_is_keyword_only() -> None: + param = inspect.signature(SwgohComlinkBase.__init__).parameters["limits"] + assert param.kind is inspect.Parameter.KEYWORD_ONLY + assert param.default is None + + +@pytest.mark.parametrize("cls", [SwgohComlink, SwgohComlinkAsync]) +@pytest.mark.parametrize("bad", [{"max_connections": 5}, 5, "limits"]) +def test_limits_must_be_httpx_limits(cls: type[SwgohComlink] | type[SwgohComlinkAsync], bad: Any) -> None: + with pytest.raises(SwgohComlinkTypeError, match="limits must be an httpx.Limits or None"): + cls(limits=bad) + + +@pytest.mark.parametrize("cls", [SwgohComlink, SwgohComlinkAsync]) +def test_limits_do_not_change_timeouts(cls: type[SwgohComlink] | type[SwgohComlinkAsync]) -> None: + client = cls(limits=httpx.Limits(keepalive_expiry=1.0)) + assert client.client.timeout == client.stats_client.timeout == httpx.Timeout(DEFAULT_TIMEOUT) diff --git a/tests/unit/test_credential_env.py b/tests/unit/test_credential_env.py new file mode 100644 index 0000000..a23f5b6 --- /dev/null +++ b/tests/unit/test_credential_env.py @@ -0,0 +1,169 @@ +"""HMAC credentials come from the namespaced COMLINK_* environment variables, with the old names deprecated.""" + +from __future__ import annotations + +import logging +import warnings +from collections.abc import Callable + +import pytest + +from swgoh_comlink import SwgohComlink, SwgohComlinkAsync + +Client = SwgohComlink | SwgohComlinkAsync + +BASE_LOGGER = "swgoh_comlink._base" +ENV_NAMES = ("COMLINK_ACCESS_KEY", "COMLINK_SECRET_KEY", "ACCESS_KEY", "SECRET_KEY") + + +@pytest.fixture(autouse=True) +def clean_env(monkeypatch: pytest.MonkeyPatch) -> None: + """Start every test with none of the credential variables set, whatever the outer shell exports.""" + for name in ENV_NAMES: + monkeypatch.delenv(name, raising=False) + + +def _build(make_comlink: Callable[..., Client], **kwargs: str) -> tuple[Client, list[warnings.WarningMessage]]: + """Build a client and return it with the DeprecationWarnings raised while constructing it.""" + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + client = make_comlink(**kwargs) + return client, [w for w in caught if issubclass(w.category, DeprecationWarning)] + + +def test_new_names_enable_hmac(make_comlink: Callable[..., Client], monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("COMLINK_ACCESS_KEY", "new_pub") + monkeypatch.setenv("COMLINK_SECRET_KEY", "new_priv") + client, deprecations = _build(make_comlink) + assert (client.hmac, client.access_key, client.secret_key) == (True, "new_pub", "new_priv") + assert deprecations == [] + + +def test_new_names_take_precedence_over_old( + make_comlink: Callable[..., Client], monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setenv("COMLINK_ACCESS_KEY", "new_pub") + monkeypatch.setenv("COMLINK_SECRET_KEY", "new_priv") + monkeypatch.setenv("ACCESS_KEY", "old_pub") + monkeypatch.setenv("SECRET_KEY", "old_priv") + client, deprecations = _build(make_comlink) + assert (client.hmac, client.access_key, client.secret_key) == (True, "new_pub", "new_priv") + assert deprecations == [] + + +def test_old_names_still_work_with_one_deprecation_warning( + make_comlink: Callable[..., Client], monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setenv("ACCESS_KEY", "old_pub") + monkeypatch.setenv("SECRET_KEY", "old_priv") + client, deprecations = _build(make_comlink) + assert (client.hmac, client.access_key, client.secret_key) == (True, "old_pub", "old_priv") + assert len(deprecations) == 1 + message = str(deprecations[0].message) + assert "COMLINK_ACCESS_KEY" in message + assert "COMLINK_SECRET_KEY" in message + assert "old_pub" not in message + assert "old_priv" not in message + + +def test_each_client_warns_once(make_comlink: Callable[..., Client], monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("ACCESS_KEY", "old_pub") + monkeypatch.setenv("SECRET_KEY", "old_priv") + assert len(_build(make_comlink)[1]) == 1 + assert len(_build(make_comlink)[1]) == 1 + + +def test_deprecation_points_at_the_caller(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("ACCESS_KEY", "old_pub") + monkeypatch.setenv("SECRET_KEY", "old_priv") + with pytest.warns(DeprecationWarning) as record: + client = SwgohComlink() + client.close() + assert record[0].filename == __file__ + + +async def test_async_deprecation_points_at_the_caller(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("ACCESS_KEY", "old_pub") + monkeypatch.setenv("SECRET_KEY", "old_priv") + with pytest.warns(DeprecationWarning) as record: + client = SwgohComlinkAsync() + await client.aclose() + assert record[0].filename == __file__ + + +def test_constructor_arguments_beat_all_env_vars( + make_comlink: Callable[..., Client], monkeypatch: pytest.MonkeyPatch +) -> None: + for name in ENV_NAMES: + monkeypatch.setenv(name, f"env_{name}") + client, deprecations = _build(make_comlink, access_key="arg_pub", secret_key="arg_priv") + assert (client.hmac, client.access_key, client.secret_key) == (True, "arg_pub", "arg_priv") + assert deprecations == [] + + +def test_constructor_argument_overrides_one_env_var( + make_comlink: Callable[..., Client], monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setenv("COMLINK_ACCESS_KEY", "new_pub") + monkeypatch.setenv("COMLINK_SECRET_KEY", "new_priv") + client, _ = _build(make_comlink, secret_key="arg_priv") + assert (client.access_key, client.secret_key) == ("new_pub", "arg_priv") + + +def test_old_names_ignored_once_a_new_name_is_set( + make_comlink: Callable[..., Client], monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture +) -> None: + """The two namespaces are never mixed: one new name stops both old names from being read.""" + monkeypatch.setenv("COMLINK_ACCESS_KEY", "new_pub") + monkeypatch.setenv("SECRET_KEY", "old_priv") + with caplog.at_level(logging.WARNING, logger=BASE_LOGGER): + client, deprecations = _build(make_comlink) + assert (client.hmac, client.access_key, client.secret_key) == (False, "new_pub", None) + assert deprecations == [] + assert "COMLINK_SECRET_KEY" in caplog.text + + +@pytest.mark.parametrize( + ("env", "missing"), + [ + ({"COMLINK_ACCESS_KEY": "new_pub"}, "secret_key"), + ({"COMLINK_SECRET_KEY": "new_priv"}, "access_key"), + ({"ACCESS_KEY": "old_pub"}, "secret_key"), + ({"SECRET_KEY": "old_priv"}, "access_key"), + ], +) +def test_half_a_pair_logs_a_warning( + make_comlink: Callable[..., Client], + monkeypatch: pytest.MonkeyPatch, + caplog: pytest.LogCaptureFixture, + env: dict[str, str], + missing: str, +) -> None: + for name, value in env.items(): + monkeypatch.setenv(name, value) + with caplog.at_level(logging.WARNING, logger=BASE_LOGGER): + client, _ = _build(make_comlink) + assert client.hmac is False + warnings_logged = [r for r in caplog.records if r.levelno == logging.WARNING and r.name == BASE_LOGGER] + assert len(warnings_logged) == 1 + text = warnings_logged[0].getMessage() + assert "HMAC" in text + assert missing in text + assert all(value not in text for value in env.values()) + + +def test_half_a_pair_from_arguments_logs_a_warning( + make_comlink: Callable[..., Client], caplog: pytest.LogCaptureFixture +) -> None: + with caplog.at_level(logging.WARNING, logger=BASE_LOGGER): + client, _ = _build(make_comlink, access_key="arg_pub") + assert client.hmac is False + assert "secret_key" in caplog.text + + +def test_no_credentials_is_silent(make_comlink: Callable[..., Client], caplog: pytest.LogCaptureFixture) -> None: + with caplog.at_level(logging.WARNING, logger=BASE_LOGGER): + client, deprecations = _build(make_comlink) + assert client.hmac is False + assert deprecations == [] + assert caplog.records == [] diff --git a/tests/unit/test_hmac_plain_http.py b/tests/unit/test_hmac_plain_http.py new file mode 100644 index 0000000..2d708e5 --- /dev/null +++ b/tests/unit/test_hmac_plain_http.py @@ -0,0 +1,114 @@ +"""A client that signs requests over plain HTTP to a non-loopback host logs one warning.""" + +from __future__ import annotations + +import logging +from collections.abc import Callable +from typing import Any + +import pytest + +from swgoh_comlink import SwgohComlink, SwgohComlinkAsync + +Client = SwgohComlink | SwgohComlinkAsync + +BASE_LOGGER = "swgoh_comlink._base" +KEYS = {"access_key": "pub_key", "secret_key": "priv_key"} + + +@pytest.fixture(autouse=True) +def clean_env(monkeypatch: pytest.MonkeyPatch) -> None: + """Keep credential variables from the outer shell from switching HMAC on.""" + for name in ("COMLINK_ACCESS_KEY", "COMLINK_SECRET_KEY", "ACCESS_KEY", "SECRET_KEY"): + monkeypatch.delenv(name, raising=False) + + +def _plain_http_warnings( + make_comlink: Callable[..., Client], caplog: pytest.LogCaptureFixture, **kwargs: Any +) -> list[logging.LogRecord]: + with caplog.at_level(logging.WARNING, logger=BASE_LOGGER): + make_comlink(**kwargs) + return [r for r in caplog.records if r.name == BASE_LOGGER and "plain HTTP" in r.getMessage()] + + +@pytest.mark.parametrize( + "kwargs", + [ + {"url": "http://comlink.example.com:3000"}, + {"url": "http://comlink.example.com"}, + {"url": "HTTP://comlink.example.com:3000"}, + {"url": "http://192.168.1.10:3000"}, + {"url": "http://[2001:db8::1]:3000"}, + {"url": "http://128.0.0.1:3000"}, + {"url": "http://localhost.example.com:3000"}, + {"host": "comlink.lab"}, + {"url": "https://comlink.example.com", "stats_url": "http://stats.example.com:3223"}, + ], + ids=lambda kwargs: next(iter(kwargs.values())), +) +def test_warns_for_plain_http_to_a_remote_host( + make_comlink: Callable[..., Client], caplog: pytest.LogCaptureFixture, kwargs: dict[str, str] +) -> None: + records = _plain_http_warnings(make_comlink, caplog, **KEYS, **kwargs) + assert len(records) == 1 + assert records[0].levelno == logging.WARNING + text = records[0].getMessage() + assert "HMAC" in text + assert "priv_key" not in text + assert "pub_key" not in text + + +def test_one_warning_when_both_urls_are_remote( + make_comlink: Callable[..., Client], caplog: pytest.LogCaptureFixture +) -> None: + records = _plain_http_warnings( + make_comlink, caplog, url="http://comlink.example.com:3000", stats_url="http://stats.example.com:3223", **KEYS + ) + assert len(records) == 1 + assert "comlink.example.com" in records[0].getMessage() + assert "stats.example.com" in records[0].getMessage() + + +def test_each_client_warns_once(make_comlink: Callable[..., Client], caplog: pytest.LogCaptureFixture) -> None: + assert len(_plain_http_warnings(make_comlink, caplog, url="http://comlink.example.com:3000", **KEYS)) == 1 + caplog.clear() + assert len(_plain_http_warnings(make_comlink, caplog, url="http://comlink.example.com:3000", **KEYS)) == 1 + + +@pytest.mark.parametrize( + "url", + [ + "http://localhost:3000", + "http://LOCALHOST:3000", + "http://localhost", + "http://127.0.0.1:3000", + "http://127.0.0.1", + "http://127.10.20.30:3000", + "http://[::1]:3000", + "https://comlink.example.com", + "https://comlink.example.com:8443", + "https://192.168.1.10:3000", + ], +) +def test_no_warning_for_loopback_or_https( + make_comlink: Callable[..., Client], caplog: pytest.LogCaptureFixture, url: str +) -> None: + assert _plain_http_warnings(make_comlink, caplog, url=url, **KEYS) == [] + + +def test_no_warning_without_keys(make_comlink: Callable[..., Client], caplog: pytest.LogCaptureFixture) -> None: + assert _plain_http_warnings(make_comlink, caplog, url="http://comlink.example.com:3000") == [] + + +def test_warns_for_env_keys( + make_comlink: Callable[..., Client], caplog: pytest.LogCaptureFixture, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setenv("COMLINK_ACCESS_KEY", "pub_key") + monkeypatch.setenv("COMLINK_SECRET_KEY", "priv_key") + assert len(_plain_http_warnings(make_comlink, caplog, url="http://comlink.example.com:3000")) == 1 + + +def test_the_connection_is_not_blocked(make_comlink: Callable[..., Client]) -> None: + client = make_comlink(url="http://comlink.example.com:3000", **KEYS) + assert client.hmac is True + assert client.url_base == "http://comlink.example.com:3000" diff --git a/tests/unit/test_response_decoding.py b/tests/unit/test_response_decoding.py index 5e2f47c..3f8db9e 100644 --- a/tests/unit/test_response_decoding.py +++ b/tests/unit/test_response_decoding.py @@ -35,3 +35,12 @@ async def test_scalar_json_is_rejected(comlink, call, httpx_mock, body): async def test_supported_response_shapes(comlink, call, httpx_mock, body): httpx_mock.add_response(json=body) assert await call(comlink, "_post", endpoint="test") == body + + +@pytest.mark.parametrize("caps", [{}, {"max_response_bytes": 1_000}], ids=["buffered", "capped"]) +async def test_utf8_bom_is_rejected(make_comlink, call, httpx_mock, caps): + """Regression guard: a BOM-prefixed body stays a decode error, as ``json.loads(str)`` rejects the BOM.""" + httpx_mock.add_response(content=b'\xef\xbb\xbf{"latestGamedataVersion": "g"}') + with pytest.raises(SwgohComlinkDecodeError) as caught: + await call(make_comlink(**caps), "get_game_metadata") + assert isinstance(caught.value.__cause__, json.JSONDecodeError) diff --git a/tests/unit/test_response_size_cap.py b/tests/unit/test_response_size_cap.py new file mode 100644 index 0000000..8ae93c8 --- /dev/null +++ b/tests/unit/test_response_size_cap.py @@ -0,0 +1,259 @@ +"""The opt-in ``max_response_bytes`` / ``max_game_data_bytes`` caps on response bodies, in both clients.""" + +from __future__ import annotations + +import gzip +import json +from collections.abc import Callable, Iterator +from typing import Any + +import httpx +import pytest +from pytest_httpx import HTTPXMock, IteratorStream + +from swgoh_comlink import RetryPolicy, SwgohComlink, SwgohComlinkAsync +from swgoh_comlink import retry as retry_module +from swgoh_comlink._base import GAME_DATA_TIMEOUT +from swgoh_comlink.exceptions import ( + SwgohComlinkHTTPError, + SwgohComlinkRateLimitError, + SwgohComlinkTypeError, + SwgohComlinkValueError, +) + +Client = SwgohComlink | SwgohComlinkAsync +CAP_ARGS = ("max_response_bytes", "max_game_data_bytes") + + +class Chunks: + """A response body served in fixed chunks that records how many chunks the client pulled.""" + + def __init__(self, body: bytes, size: int) -> None: + self.parts = [body[i : i + size] for i in range(0, len(body), size)] + self.served = 0 + + def __iter__(self) -> Iterator[bytes]: + for part in self.parts: + self.served += 1 + yield part + + +def padded_json(size: int) -> bytes: + """A JSON array of exactly *size* bytes.""" + return b"[" + b" " * (size - 2) + b"]" + + +@pytest.fixture +def no_stream(monkeypatch: pytest.MonkeyPatch) -> Callable[[Client], None]: + """Make ``client.stream`` fail, to prove a request did not take the streaming path.""" + + def patch(comlink: Client) -> None: + def boom(*args: Any, **kwargs: Any) -> None: + raise AssertionError("client.stream() must not be used without a cap") + + for http_client in (comlink.client, comlink.stats_client): + monkeypatch.setattr(http_client, "stream", boom) + + return patch + + +# ── Constructor ────────────────────────────────────────────────────────── + + +@pytest.mark.parametrize("arg", CAP_ARGS) +async def test_caps_default_to_none(comlink: Client, arg: str) -> None: + assert getattr(comlink, arg) is None + + +@pytest.mark.parametrize("arg", CAP_ARGS) +async def test_caps_are_stored(make_comlink: Callable[..., Client], arg: str) -> None: + assert getattr(make_comlink(**{arg: 1024}), arg) == 1024 + + +@pytest.mark.parametrize("arg", CAP_ARGS) +@pytest.mark.parametrize("value", [0, -1]) +async def test_caps_must_be_positive(make_comlink: Callable[..., Client], arg: str, value: int) -> None: + with pytest.raises(SwgohComlinkValueError, match=arg): + make_comlink(**{arg: value}) + + +@pytest.mark.parametrize("arg", CAP_ARGS) +@pytest.mark.parametrize("value", ["1024", 1024.0, True]) +async def test_caps_must_be_int(make_comlink: Callable[..., Client], arg: str, value: object) -> None: + with pytest.raises(SwgohComlinkTypeError, match=arg): + make_comlink(**{arg: value}) + + +# ── Default path is unchanged ──────────────────────────────────────────── + + +async def test_no_cap_does_not_stream(comlink: Client, call, httpx_mock: HTTPXMock, no_stream) -> None: + no_stream(comlink) + httpx_mock.add_response(json={"latestGamedataVersion": "g"}) + httpx_mock.add_response(json={"units": []}) + assert await call(comlink, "get_game_metadata") == {"latestGamedataVersion": "g"} + assert await call(comlink, "get_game_data", version="g") == {"units": []} + + +async def test_game_data_cap_alone_leaves_other_endpoints_unstreamed( + make_comlink: Callable[..., Client], call, httpx_mock: HTTPXMock, no_stream +) -> None: + comlink = make_comlink(max_game_data_bytes=10) + no_stream(comlink) + httpx_mock.add_response(content=padded_json(100)) + assert await call(comlink, "get_game_metadata") == [] + + +async def test_response_cap_alone_leaves_game_data_unstreamed( + make_comlink: Callable[..., Client], call, httpx_mock: HTTPXMock, no_stream +) -> None: + comlink = make_comlink(max_response_bytes=10) + no_stream(comlink) + httpx_mock.add_response(content=b'{"units": []' + b" " * 100 + b"}") + assert await call(comlink, "get_game_data", version="g") == {"units": []} + + +# ── Oversized bodies ───────────────────────────────────────────────────── + + +async def test_oversized_body_raises_and_stops_reading( + make_comlink: Callable[..., Client], call, httpx_mock: HTTPXMock +) -> None: + comlink = make_comlink(max_response_bytes=100) + body = Chunks(padded_json(500), 50) + httpx_mock.add_response(stream=IteratorStream(body)) + with pytest.raises(SwgohComlinkValueError, match=r"/metadata.*max_response_bytes.*100"): + await call(comlink, "get_game_metadata") + assert body.served == 3 # stopped at the first chunk past the cap + + +async def test_body_at_cap_is_accepted(make_comlink: Callable[..., Client], call, httpx_mock: HTTPXMock) -> None: + comlink = make_comlink(max_response_bytes=100) + httpx_mock.add_response(stream=IteratorStream(Chunks(padded_json(100), 30))) + assert await call(comlink, "get_game_metadata") == [] + + +async def test_content_length_over_cap_fails_before_reading( + make_comlink: Callable[..., Client], call, httpx_mock: HTTPXMock +) -> None: + comlink = make_comlink(max_response_bytes=100) + body = Chunks(padded_json(500), 50) + httpx_mock.add_response(headers={"Content-Length": "500"}, stream=IteratorStream(body)) + with pytest.raises(SwgohComlinkValueError, match=r"500 bytes.*max_response_bytes.*100"): + await call(comlink, "get_game_metadata") + assert body.served == 0 + + +async def test_decompressed_size_is_what_counts( + make_comlink: Callable[..., Client], call, httpx_mock: HTTPXMock +) -> None: + """A small gzip body that inflates past the cap is stopped: Content-Length gives only the compressed size.""" + compressed = gzip.compress(padded_json(1_000_000)) + assert len(compressed) < 10_000 + comlink = make_comlink(max_response_bytes=10_000) + httpx_mock.add_response( + headers={"Content-Encoding": "gzip", "Content-Length": str(len(compressed))}, + stream=IteratorStream(Chunks(compressed, 512)), + ) + with pytest.raises(SwgohComlinkValueError, match="max_response_bytes"): + await call(comlink, "get_game_metadata") + + +async def test_game_data_uses_its_own_cap(make_comlink: Callable[..., Client], call, httpx_mock: HTTPXMock) -> None: + comlink = make_comlink(max_response_bytes=10, max_game_data_bytes=1_000) + httpx_mock.add_response(content=padded_json(500)) + assert await call(comlink, "get_game_data", version="g") == [] + httpx_mock.add_response(content=padded_json(2_000)) + with pytest.raises(SwgohComlinkValueError, match=r"/data.*max_game_data_bytes.*1000"): + await call(comlink, "get_game_data", version="g") + + +async def test_stats_service_uses_response_cap( + make_comlink: Callable[..., Client], call, httpx_mock: HTTPXMock +) -> None: + comlink = make_comlink(max_response_bytes=10, max_game_data_bytes=1_000) + httpx_mock.add_response(content=padded_json(100)) + with pytest.raises(SwgohComlinkValueError, match="max_response_bytes"): + await call(comlink, "get_unit_stats", request_payload=[]) + + +# ── The request itself is unchanged ────────────────────────────────────── + + +@pytest.mark.parametrize("caps", [{}, {"max_response_bytes": 10**6, "max_game_data_bytes": 10**6}]) +async def test_streamed_request_matches_buffered_request( + make_comlink: Callable[..., Client], call, httpx_mock: HTTPXMock, caps: dict[str, int] +) -> None: + comlink = make_comlink(access_key="access", secret_key="secret", **caps) + httpx_mock.add_response(json={}) + await call(comlink, "get_game_data", version="g", items=1) + request = httpx_mock.get_request() + assert request is not None + assert request.method == "POST" + assert request.url == "http://localhost:3000/data" + assert json.loads(request.content)["payload"]["version"] == "g" + assert request.headers["Authorization"].startswith("HMAC-SHA256 ") + assert request.extensions["timeout"]["read"] == GAME_DATA_TIMEOUT + + +# ── Error statuses ─────────────────────────────────────────────────────── + +RATE_LIMIT_BODY = b'{"code": "RATE_LIMITED", "message": "slow down"}' + + +async def test_error_within_cap_matches_uncapped_error( + make_comlink: Callable[..., Client], call, httpx_mock: HTTPXMock +) -> None: + errors = [] + for caps in ({}, {"max_response_bytes": 1_000}): + httpx_mock.add_response(status_code=429, headers={"Retry-After": "3"}, content=RATE_LIMIT_BODY) + with pytest.raises(SwgohComlinkRateLimitError) as caught: + await call(make_comlink(**caps), "get_game_metadata") + errors.append(caught.value) + uncapped, capped = errors + assert str(capped) == str(uncapped) + assert (capped.status, capped.code, capped.detail, capped.retry_after) == (429, "RATE_LIMITED", "slow down", 3.0) + assert capped.response is not None + assert capped.response.content == RATE_LIMIT_BODY + assert capped.response.headers["Retry-After"] == "3" + assert isinstance(capped.__cause__, httpx.HTTPStatusError) + + +async def test_error_body_over_cap_is_cut_to_cap( + make_comlink: Callable[..., Client], call, httpx_mock: HTTPXMock +) -> None: + """An error body is read only up to the cap; the status still decides the exception class.""" + comlink = make_comlink(max_response_bytes=100) + body = Chunks(b'{"code": "GAME_6", "message": "Rate exceeded!"}' + b" " * 10_000, 64) + httpx_mock.add_response(status_code=502, headers={"Content-Length": "10047"}, stream=IteratorStream(body)) + with pytest.raises(SwgohComlinkRateLimitError) as caught: + await call(comlink, "get_game_metadata") + assert caught.value.status == 502 + assert caught.value.response is not None + assert len(caught.value.response.content) == 100 + assert body.served == 2 + + +async def test_gzip_error_body_is_decoded(make_comlink: Callable[..., Client], call, httpx_mock: HTTPXMock) -> None: + comlink = make_comlink(max_response_bytes=1_000) + httpx_mock.add_response( + status_code=400, headers={"Content-Encoding": "gzip"}, stream=IteratorStream([gzip.compress(b"bad")]) + ) + with pytest.raises(SwgohComlinkHTTPError, match="HTTP 400: bad") as caught: + await call(comlink, "get_game_metadata") + assert caught.value.response is not None + assert "content-encoding" not in caught.value.response.headers + + +async def test_retry_policy_still_retries_with_a_cap( + make_comlink: Callable[..., Client], call, httpx_mock: HTTPXMock, monkeypatch: pytest.MonkeyPatch +) -> None: + async def no_wait(seconds: float) -> None: + return None + + monkeypatch.setattr(retry_module, "_sleep", lambda seconds: None) + monkeypatch.setattr(retry_module, "_async_sleep", no_wait) + comlink = make_comlink(max_response_bytes=1_000, retry=RetryPolicy(attempts=2)) + httpx_mock.add_response(status_code=503, headers={"Retry-After": "0"}) + httpx_mock.add_response(json={"ok": True}) + assert await call(comlink, "get_game_metadata") == {"ok": True} diff --git a/tests/unit/test_unit_stats_query.py b/tests/unit/test_unit_stats_query.py new file mode 100644 index 0000000..7e6a440 --- /dev/null +++ b/tests/unit/test_unit_stats_query.py @@ -0,0 +1,123 @@ +"""The stats ``language`` query parameter is validated and encoded before it reaches the URL.""" + +from __future__ import annotations + +import hashlib +import hmac +import json +import logging +from collections.abc import Awaitable, Callable +from typing import Any, cast + +import pytest +from pytest_httpx import HTTPXMock + +from swgoh_comlink import SwgohComlink, SwgohComlinkAsync +from swgoh_comlink._base import SwgohComlinkBase +from swgoh_comlink.exceptions import SwgohComlinkValueError + +Client = SwgohComlink | SwgohComlinkAsync +Call = Callable[..., Awaitable[Any]] + +STATS_URL = "http://localhost:3223" +BASE_LOGGER = "swgoh_comlink._base" + +build = SwgohComlinkBase._build_unit_stats_endpoint + + +@pytest.mark.parametrize( + "language", + [ + "eng_us&flags=onlyGP#x", + "eng_us#x", + "eng_us&x=1", + "eng=us", + "eng/us", + "eng_us\n", + " eng_us", + "eng us", + "english", + "e_us", + "engl_us", + "eng_usa", + "éng_us", + ], +) +def test_value_that_is_not_a_language_code_raises(language: str) -> None: + with pytest.raises(SwgohComlinkValueError, match="language"): + build(flags=["calcGP"], language=language) + + +def test_non_string_language_raises() -> None: + with pytest.raises(SwgohComlinkValueError, match="language"): + build(language=cast(Any, 42)) + + +@pytest.mark.parametrize( + ("flags", "language", "expected"), + [ + (["calcGP"], "eng_us", "api?flags=calcGP&language=eng_us"), + (["calcGP", "onlyGP"], "eng_us", "api?flags=calcGP,onlyGP&language=eng_us"), + (None, "eng_us", "api?language=eng_us"), + (["calcGP"], None, "api?flags=calcGP"), + (None, None, "api"), + ], +) +def test_valid_input_builds_the_same_endpoint_as_before( + flags: list[str] | None, language: str | None, expected: str +) -> None: + assert build(flags=flags, language=language) == expected + + +@pytest.mark.parametrize("language", ["eng_us", "ENG_US", "Ger_De"]) +def test_known_language_is_accepted_without_a_warning(language: str, caplog: pytest.LogCaptureFixture) -> None: + with caplog.at_level(logging.WARNING, logger=BASE_LOGGER): + assert build(language=language) == f"api?language={language}" + + assert [r for r in caplog.records if r.levelno >= logging.WARNING] == [] + + +def test_unknown_well_formed_language_warns_once_and_is_still_sent(caplog: pytest.LogCaptureFixture) -> None: + with caplog.at_level(logging.WARNING, logger=BASE_LOGGER): + assert build(flags=["calcGP"], language="eng_uk") == "api?flags=calcGP&language=eng_uk" + + warnings = [r for r in caplog.records if r.levelno >= logging.WARNING] + assert len(warnings) == 1 + assert "eng_uk" in warnings[0].getMessage() + assert "eng_us" in warnings[0].getMessage() + + +async def test_client_rejects_injection_before_sending(comlink: Client, call: Call, httpx_mock: HTTPXMock) -> None: + with pytest.raises(SwgohComlinkValueError, match="language"): + await call(comlink, "get_unit_stats", request_payload=[{"unit": "data"}], language="eng_us&flags=onlyGP#x") + + assert httpx_mock.get_requests() == [] + + +async def test_hmac_signature_matches_a_request_path_with_a_query_string( + make_comlink: Callable[..., Client], call: Call, httpx_mock: HTTPXMock +) -> None: + httpx_mock.add_response(json=[{"unit": "data"}]) + + await call( + make_comlink(access_key="pub", secret_key="priv"), + "get_unit_stats", + request_payload=[{"unit": "data"}], + flags=["calcGP", "gameStyle"], + language="eng_us", + ) + + request = httpx_mock.get_request() + assert request is not None + assert str(request.url) == f"{STATS_URL}/api?flags=calcGP,gameStyle&language=eng_us" + # Recompute from the request as it arrived: the signed path must be byte-identical to the + # path and query on the wire. + signed_path = request.url.raw_path + assert signed_path == b"/api?flags=calcGP,gameStyle&language=eng_us" + body = json.loads(request.content) + signature = hmac.new(b"priv", digestmod=hashlib.sha256) + signature.update(request.headers["X-Date"].encode()) + signature.update(request.method.encode()) + signature.update(signed_path) + signature.update(hashlib.md5(json.dumps(body, separators=(",", ":")).encode()).hexdigest().encode()) # noqa: S324 + assert request.headers["Authorization"] == f"HMAC-SHA256 Credential=pub,Signature={signature.hexdigest()}"