diff --git a/README.md b/README.md index a1564cd..578c5a9 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,59 @@ It is generated with [Stainless](https://www.stainless.com/). The REST API documentation can be found on [lim.run](https://lim.run). The full API of this library can be found in [api.md](api.md). +## Workload identity federation + +Authenticate with a JWT from your identity provider after an organization admin +creates a [federation binding](https://docs.limrun.com/docs/platform/workload-identity-federation). +Point the client at a file your runtime keeps current, such as a Kubernetes projected token: + +```python +client = Limrun( + workload_token_file="/var/run/identity/token", + binding_id="binding_REPLACE_WITH_BINDING_ID", +) +``` + +Or pass the JWT itself in `workload_token`. A string is exchanged as is on every renewal, so it +stops working once that JWT expires. Pass a callable instead when the client outlives the JWT; +the SDK calls it for every exchange. `AsyncLimrun` also accepts an async callable: + +```python +client = Limrun( + workload_token=lambda: get_id_token_from_your_provider(), + binding_id="binding_REPLACE_WITH_BINDING_ID", +) +``` + +Some platforms never show the JWT to the workload. Their egress proxy adds it to outbound +requests instead. Configure the proxy to send the JWT to `sts.limrun.com` in the +`X-Limrun-Subject-Token` header, and tell the client not to send one: + +```python +client = Limrun( + workload_token_injected=True, + binding_id="binding_REPLACE_WITH_BINDING_ID", +) +``` + +`workload_token_injected` cannot be combined with another source. If the proxy terminates TLS +with its own certificate authority, point `SSL_CERT_FILE` at a bundle that includes it. + +Alternatively, set `LIMRUN_WORKLOAD_IDENTITY_BINDING_ID` and one of +`LIMRUN_WORKLOAD_IDENTITY_TOKEN` (the JWT), `LIMRUN_WORKLOAD_IDENTITY_TOKEN_FILE`, or +`LIMRUN_WORKLOAD_IDENTITY_TOKEN_INJECTED=true`, and use the default client constructor. Explicit options take precedence over environment variables, +and a token over a file. An API key takes precedence over workload identity when configured. +The SDK caches a short-lived Limrun access token and reads the identity again on renewal. +The access token never outlives the JWT it was exchanged for. `LIMRUN_STS_BASE_URL` overrides +the default token service at `https://sts.limrun.com`. + +The instance's `status.token` grants `control` on that instance. It permits runtime +operations and reading the instance record, but cannot create, update, or delete +instance records. Use your configured API key or federated client for those calls, +with the corresponding `create`, `update`, or `delete` permission. Existing `all` +grants include both runtime control and lifecycle management. See the +[permissions reference](https://docs.limrun.com/docs/reference/permissions). + ## Installation ```sh diff --git a/src/limrun_api/_client.py b/src/limrun_api/_client.py index bbd3d38..55efd38 100644 --- a/src/limrun_api/_client.py +++ b/src/limrun_api/_client.py @@ -22,6 +22,7 @@ ) from ._utils import is_given, get_async_library from ._compat import cached_property +from ._models import FinalRequestOptions from ._version import __version__ from ._streaming import Stream as Stream, AsyncStream as AsyncStream from ._exceptions import APIStatusError @@ -30,6 +31,15 @@ SyncAPIClient, AsyncAPIClient, ) +from ._workload_identity import ( + WorkloadToken, + WorkloadIdentity, + AsyncWorkloadToken, + AsyncWorkloadIdentity, + replace_identity, + resolve_identity, + resolve_injected, +) if TYPE_CHECKING: from .resources import assets, ios_instances, xcode_instances, android_instances @@ -44,11 +54,17 @@ class Limrun(SyncAPIClient): # client options api_key: str | None + workload_token: WorkloadToken | None def __init__( self, *, api_key: str | None = None, + workload_token: WorkloadToken | None = None, + workload_token_file: str | None = None, + workload_token_injected: bool | None = None, + binding_id: str | None = None, + sts_base_url: str | None = None, base_url: str | httpx.URL | None = None, timeout: float | Timeout | None | NotGiven = not_given, max_retries: int = DEFAULT_MAX_RETRIES, @@ -75,6 +91,35 @@ def __init__( if api_key is None: api_key = os.environ.get("LIM_API_KEY") self.api_key = api_key + self.workload_token, self.workload_token_file = resolve_identity(workload_token, workload_token_file) + self.workload_token_injected = resolve_injected(workload_token_injected) + if not api_key and self.workload_token_injected and (self.workload_token or self.workload_token_file): + # The proxy decides which JWT the exchange carries, so a second source would be ignored. + raise ValueError( + "workload_token_injected cannot be combined with workload_token, workload_token_file, " + "or their environment variables" + ) + has_identity = bool(self.workload_token or self.workload_token_file or self.workload_token_injected) + self.binding_id = binding_id or os.environ.get("LIMRUN_WORKLOAD_IDENTITY_BINDING_ID") + self.sts_base_url = sts_base_url or os.environ.get("LIMRUN_STS_BASE_URL") or "https://sts.limrun.com" + if not api_key and self.binding_id and not has_identity: + raise ValueError( + "Federation requires workload_token, workload_token_file, LIMRUN_WORKLOAD_IDENTITY_TOKEN, " + "or LIMRUN_WORKLOAD_IDENTITY_TOKEN_FILE" + ) + if not api_key and has_identity and not self.binding_id: + raise ValueError("Federation requires binding_id or LIMRUN_WORKLOAD_IDENTITY_BINDING_ID") + self._workload_identity = ( + WorkloadIdentity( + self.workload_token_file, + self.binding_id, + self.sts_base_url, + self.workload_token, + self.workload_token_injected, + ) + if not api_key and has_identity and self.binding_id + else None + ) if base_url is None: base_url = os.environ.get("LIMRUN_BASE_URL") @@ -92,6 +137,15 @@ def __init__( _strict_response_validation=_strict_response_validation, ) + @override + def _prepare_options(self, options: FinalRequestOptions) -> FinalRequestOptions: + if self._workload_identity is not None: + headers = dict(options.headers) if not isinstance(options.headers, NotGiven) else {} + if not any(key.lower() == "authorization" for key in {**self._custom_headers, **headers}): + headers["Authorization"] = "Bearer " + self._workload_identity.get(self._client) + options.headers = headers + return options + @cached_property def android_instances(self) -> AndroidInstancesResource: from .resources.android_instances import AndroidInstancesResource @@ -159,6 +213,11 @@ def copy( self, *, api_key: str | None = None, + workload_token: WorkloadToken | None = None, + workload_token_file: str | None = None, + workload_token_injected: bool | None = None, + binding_id: str | None = None, + sts_base_url: str | None = None, base_url: str | httpx.URL | None = None, timeout: float | Timeout | None | NotGiven = not_given, http_client: httpx.Client | None = None, @@ -190,9 +249,21 @@ def copy( elif set_default_query is not None: params = set_default_query + identity = replace_identity( + workload_token, + workload_token_file, + workload_token_injected, + (self.workload_token, self.workload_token_file, self.workload_token_injected), + ) http_client = http_client or self._client - return self.__class__( + client = self.__class__( api_key=api_key or self.api_key, + # A new file replaces the current token, so it is not overridden by it. + workload_token=identity[0], + workload_token_file=identity[1], + workload_token_injected=identity[2], + binding_id=binding_id or self.binding_id, + sts_base_url=sts_base_url or self.sts_base_url, base_url=base_url or self.base_url, timeout=self.timeout if isinstance(timeout, NotGiven) else timeout, http_client=http_client, @@ -201,6 +272,16 @@ def copy( default_query=params, **_extra_kwargs, ) + if ( + client.api_key == self.api_key + and client.workload_token is self.workload_token + and client.workload_token_file == self.workload_token_file + and client.workload_token_injected == self.workload_token_injected + and client.binding_id == self.binding_id + and client.sts_base_url == self.sts_base_url + ): + client._workload_identity = self._workload_identity + return client # Alias for `copy` for nicer inline usage, e.g. # client.with_options(timeout=10).foo.create(...) @@ -243,11 +324,17 @@ def _make_status_error( class AsyncLimrun(AsyncAPIClient): # client options api_key: str | None + workload_token: AsyncWorkloadToken | None def __init__( self, *, api_key: str | None = None, + workload_token: AsyncWorkloadToken | None = None, + workload_token_file: str | None = None, + workload_token_injected: bool | None = None, + binding_id: str | None = None, + sts_base_url: str | None = None, base_url: str | httpx.URL | None = None, timeout: float | Timeout | None | NotGiven = not_given, max_retries: int = DEFAULT_MAX_RETRIES, @@ -274,6 +361,35 @@ def __init__( if api_key is None: api_key = os.environ.get("LIM_API_KEY") self.api_key = api_key + self.workload_token, self.workload_token_file = resolve_identity(workload_token, workload_token_file) + self.workload_token_injected = resolve_injected(workload_token_injected) + if not api_key and self.workload_token_injected and (self.workload_token or self.workload_token_file): + # The proxy decides which JWT the exchange carries, so a second source would be ignored. + raise ValueError( + "workload_token_injected cannot be combined with workload_token, workload_token_file, " + "or their environment variables" + ) + has_identity = bool(self.workload_token or self.workload_token_file or self.workload_token_injected) + self.binding_id = binding_id or os.environ.get("LIMRUN_WORKLOAD_IDENTITY_BINDING_ID") + self.sts_base_url = sts_base_url or os.environ.get("LIMRUN_STS_BASE_URL") or "https://sts.limrun.com" + if not api_key and self.binding_id and not has_identity: + raise ValueError( + "Federation requires workload_token, workload_token_file, LIMRUN_WORKLOAD_IDENTITY_TOKEN, " + "or LIMRUN_WORKLOAD_IDENTITY_TOKEN_FILE" + ) + if not api_key and has_identity and not self.binding_id: + raise ValueError("Federation requires binding_id or LIMRUN_WORKLOAD_IDENTITY_BINDING_ID") + self._workload_identity = ( + AsyncWorkloadIdentity( + self.workload_token_file, + self.binding_id, + self.sts_base_url, + self.workload_token, + self.workload_token_injected, + ) + if not api_key and has_identity and self.binding_id + else None + ) if base_url is None: base_url = os.environ.get("LIMRUN_BASE_URL") @@ -291,6 +407,15 @@ def __init__( _strict_response_validation=_strict_response_validation, ) + @override + async def _prepare_options(self, options: FinalRequestOptions) -> FinalRequestOptions: + if self._workload_identity is not None: + headers = dict(options.headers) if not isinstance(options.headers, NotGiven) else {} + if not any(key.lower() == "authorization" for key in {**self._custom_headers, **headers}): + headers["Authorization"] = "Bearer " + await self._workload_identity.get(self._client) + options.headers = headers + return options + @cached_property def android_instances(self) -> AsyncAndroidInstancesResource: from .resources.android_instances import AsyncAndroidInstancesResource @@ -358,6 +483,11 @@ def copy( self, *, api_key: str | None = None, + workload_token: AsyncWorkloadToken | None = None, + workload_token_file: str | None = None, + workload_token_injected: bool | None = None, + binding_id: str | None = None, + sts_base_url: str | None = None, base_url: str | httpx.URL | None = None, timeout: float | Timeout | None | NotGiven = not_given, http_client: httpx.AsyncClient | None = None, @@ -389,9 +519,21 @@ def copy( elif set_default_query is not None: params = set_default_query + identity = replace_identity( + workload_token, + workload_token_file, + workload_token_injected, + (self.workload_token, self.workload_token_file, self.workload_token_injected), + ) http_client = http_client or self._client - return self.__class__( + client = self.__class__( api_key=api_key or self.api_key, + # A new file replaces the current token, so it is not overridden by it. + workload_token=identity[0], + workload_token_file=identity[1], + workload_token_injected=identity[2], + binding_id=binding_id or self.binding_id, + sts_base_url=sts_base_url or self.sts_base_url, base_url=base_url or self.base_url, timeout=self.timeout if isinstance(timeout, NotGiven) else timeout, http_client=http_client, @@ -400,6 +542,16 @@ def copy( default_query=params, **_extra_kwargs, ) + if ( + client.api_key == self.api_key + and client.workload_token is self.workload_token + and client.workload_token_file == self.workload_token_file + and client.workload_token_injected == self.workload_token_injected + and client.binding_id == self.binding_id + and client.sts_base_url == self.sts_base_url + ): + client._workload_identity = self._workload_identity + return client # Alias for `copy` for nicer inline usage, e.g. # client.with_options(timeout=10).foo.create(...) diff --git a/src/limrun_api/_workload_identity.py b/src/limrun_api/_workload_identity.py new file mode 100644 index 0000000..ef7bb88 --- /dev/null +++ b/src/limrun_api/_workload_identity.py @@ -0,0 +1,169 @@ +from __future__ import annotations + +import os +import time +import inspect +import threading +from typing import Dict, Tuple, Union, TypeVar, Callable, Optional, Awaitable +from pathlib import Path + +import anyio +import httpx +from anyio.to_thread import run_sync + +WorkloadToken = Union[str, Callable[[], str]] +"""A workload JWT, or a callable that returns the current one for every exchange.""" + +AsyncWorkloadToken = Union[str, Callable[[], Union[str, Awaitable[str]]]] +"""A workload JWT, or a callable, sync or async, that returns the current one for every exchange.""" + + +_Token = TypeVar("_Token") + + +def resolve_identity( + token: Optional[_Token], token_file: Optional[str] +) -> Tuple[Union[_Token, str, None], Optional[str]]: + """Explicit options before environment variables, and a token before a file.""" + if token: + return token, None + if token_file: + return None, token_file + env_token = os.environ.get("LIMRUN_WORKLOAD_IDENTITY_TOKEN") + if env_token: + return env_token, None + return None, os.environ.get("LIMRUN_WORKLOAD_IDENTITY_TOKEN_FILE") or None + + +def replace_identity( + token: Optional[_Token], + token_file: Optional[str], + injected: Optional[bool], + current: Tuple[Optional[_Token], Optional[str], bool], +) -> Tuple[Optional[_Token], Optional[str], bool]: + """A source passed to copy() replaces the client's current one rather than combining with it.""" + if token or token_file or injected: + return token, token_file, bool(injected) + current_token, current_file, current_injected = current + return current_token, current_file, current_injected if injected is None else injected + + +def resolve_injected(injected: Optional[bool]) -> bool: + if injected is not None: + return injected + return os.environ.get("LIMRUN_WORKLOAD_IDENTITY_TOKEN_INJECTED", "").strip().lower() in ("1", "true") + + +def _read_token_file(path: str) -> str: + with Path(path).open(encoding="utf-8") as source: + return source.read(32769) + + +def _identity_form(identity: object, binding: str, injected: bool = False) -> Dict[str, str]: + form = { + "grant_type": "urn:ietf:params:oauth:grant-type:token-exchange", + "subject_token_type": "urn:ietf:params:oauth:token-type:jwt", + "audience": binding, + } + # An egress proxy adds the JWT in the X-Limrun-Subject-Token header, so the client sends none. + if injected: + return form + token = identity.strip() if isinstance(identity, str) else "" + if not token or len(token) > 32768: + raise ValueError("Workload identity token must be a JWT of at most 32768 characters") + form["subject_token"] = token + return form + + +def _session(response: httpx.Response, started: float) -> Tuple[str, float]: + if response.status_code != 200: + raise RuntimeError(f"Workload token exchange returned HTTP {response.status_code}") + try: + result = response.json() + token = result["access_token"] + ttl = result["expires_in"] + if not isinstance(token, str) or not token or result["token_type"] != "Bearer": + raise ValueError() + if type(ttl) is not int or not 1 <= ttl <= 14400: + raise ValueError() + except (KeyError, ValueError, TypeError): + raise RuntimeError("Invalid workload token exchange response") from None + expires = started + ttl + if expires <= time.monotonic(): + raise RuntimeError("Exchanged workload token has already expired") + return token, expires - min(60, ttl / 5) + + +class WorkloadIdentity: + def __init__( + self, + token_file: Optional[str], + binding: str, + endpoint: str, + token: Optional[WorkloadToken] = None, + injected: bool = False, + ) -> None: + self.token = token + self.injected = injected + self.token_file = token_file + self.binding = binding + self.endpoint = endpoint.rstrip("/") + "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/v1/access_tokens" + self.session = "" + self.refresh_at = 0.0 + self.lock = threading.Lock() + + def _identity(self) -> str: + if self.token is not None: + return self.token() if callable(self.token) else self.token + if not self.token_file: + raise ValueError("Workload identity requires a token or token file") + return _read_token_file(self.token_file) + + def get(self, client: httpx.Client) -> str: + with self.lock: + if time.monotonic() < self.refresh_at: + return self.session + form = _identity_form(None if self.injected else self._identity(), self.binding, self.injected) + started = time.monotonic() + response = client.post(self.endpoint, data=form, timeout=30, follow_redirects=False) + self.session, self.refresh_at = _session(response, started) + return self.session + + +class AsyncWorkloadIdentity: + def __init__( + self, + token_file: Optional[str], + binding: str, + endpoint: str, + token: Optional[AsyncWorkloadToken] = None, + injected: bool = False, + ) -> None: + self.token = token + self.injected = injected + self.token_file = token_file + self.binding = binding + self.endpoint = endpoint.rstrip("/") + "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/v1/access_tokens" + self.session = "" + self.refresh_at = 0.0 + self.lock = anyio.Lock() + + async def _identity(self) -> object: + if self.token is not None: + if not callable(self.token): + return self.token + result = self.token() + return await result if inspect.isawaitable(result) else result + if not self.token_file: + raise ValueError("Workload identity requires a token or token file") + return await run_sync(_read_token_file, self.token_file) + + async def get(self, client: httpx.AsyncClient) -> str: + async with self.lock: + if time.monotonic() < self.refresh_at: + return self.session + form = _identity_form(None if self.injected else await self._identity(), self.binding, self.injected) + started = time.monotonic() + response = await client.post(self.endpoint, data=form, timeout=30, follow_redirects=False) + self.session, self.refresh_at = _session(response, started) + return self.session diff --git a/tests/test_workload_identity.py b/tests/test_workload_identity.py new file mode 100644 index 0000000..0369190 --- /dev/null +++ b/tests/test_workload_identity.py @@ -0,0 +1,368 @@ +from __future__ import annotations + +import asyncio +from pathlib import Path +from urllib.parse import parse_qs +from concurrent.futures import ThreadPoolExecutor + +import httpx +import pytest + +from limrun_api import Limrun, AsyncLimrun +from limrun_api._workload_identity import WorkloadIdentity, AsyncWorkloadIdentity + + +def test_rotation_and_concurrent_exchange(tmp_path: Path) -> None: + path = tmp_path / "identity.jwt" + path.write_text("first.jwt\n") + identities: list[str] = [] + + def exchange(request: httpx.Request) -> httpx.Response: + form = parse_qs(request.content.decode()) + assert form["audience"] == ["binding_builds"] + assert "authorization" not in request.headers + identities.append(form["subject_token"][0]) + return httpx.Response(200, json={"access_token": "lim_st_session", "token_type": "Bearer", "expires_in": 300}) + + identity = WorkloadIdentity(str(path), "binding_builds", "https://sts.example.com") + with httpx.Client(transport=httpx.MockTransport(exchange)) as client: + + def get_session(_: int) -> str: + return identity.get(client) + + with ThreadPoolExecutor(max_workers=8) as pool: + assert list(pool.map(get_session, range(16))) == ["lim_st_session"] * 16 + assert identities == ["first.jwt"] + path.write_text("rotated.jwt") + identity.refresh_at = 0 + assert identity.get(client) == "lim_st_session" + assert identities == ["first.jwt", "rotated.jwt"] + + +async def test_async_rotation_and_concurrent_exchange(tmp_path: Path) -> None: + path = tmp_path / "identity.jwt" + path.write_text("first.jwt") + identities: list[str] = [] + + def exchange(request: httpx.Request) -> httpx.Response: + identities.append(parse_qs(request.content.decode())["subject_token"][0]) + return httpx.Response(200, json={"access_token": "lim_st_session", "token_type": "Bearer", "expires_in": 300}) + + identity = AsyncWorkloadIdentity(str(path), "binding_builds", "https://sts.example.com") + async with httpx.AsyncClient(transport=httpx.MockTransport(exchange)) as client: + assert await asyncio.gather(*(identity.get(client) for _ in range(16))) == ["lim_st_session"] * 16 + assert identities == ["first.jwt"] + path.write_text("rotated.jwt") + identity.refresh_at = 0 + await identity.get(client) + assert identities == ["first.jwt", "rotated.jwt"] + + +@pytest.mark.parametrize("asynchronous", [False, True]) +async def test_sdk_uses_session_and_copy_preserves_identity( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, asynchronous: bool +) -> None: + monkeypatch.delenv("LIM_API_KEY", raising=False) + path = tmp_path / "identity.jwt" + path.write_text("external.jwt") + monkeypatch.setenv("LIMRUN_WORKLOAD_IDENTITY_TOKEN_FILE", str(path)) + monkeypatch.setenv("LIMRUN_WORKLOAD_IDENTITY_BINDING_ID", "binding_builds") + monkeypatch.setenv("LIMRUN_STS_BASE_URL", "https://sts.example.com") + exchanges = 0 + + def handle(request: httpx.Request) -> httpx.Response: + nonlocal exchanges + if request.url.host == "sts.example.com": + assert request.url.path == "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/v1/access_tokens" + assert parse_qs(request.content.decode())["subject_token"] == ["external.jwt"] + exchanges += 1 + return httpx.Response( + 200, json={"access_token": "lim_st_session", "token_type": "Bearer", "expires_in": 300} + ) + assert request.headers["authorization"] == "Bearer lim_st_session" + assert b"external.jwt" not in request.content + return httpx.Response(200, json={"items": []}) + + if asynchronous: + async with AsyncLimrun(http_client=httpx.AsyncClient(transport=httpx.MockTransport(handle))) as client: + await client.android_instances.list() + await client.with_options(timeout=5).android_instances.list() + await client.with_options(timeout=10).android_instances.list() + assert client.with_options(binding_id="binding_other")._workload_identity is not client._workload_identity + assert ( + client.with_options(workload_token_file="other.jwt")._workload_identity is not client._workload_identity + ) + assert ( + client.with_options(sts_base_url="https://other.example")._workload_identity + is not client._workload_identity + ) + assert client.with_options(api_key="key")._workload_identity is None + else: + with Limrun(http_client=httpx.Client(transport=httpx.MockTransport(handle))) as sync_client: + sync_client.android_instances.list() + sync_client.with_options(timeout=5).android_instances.list() + sync_client.with_options(timeout=10).android_instances.list() + assert ( + sync_client.with_options(binding_id="binding_other")._workload_identity + is not sync_client._workload_identity + ) + assert ( + sync_client.with_options(workload_token_file="other.jwt")._workload_identity + is not sync_client._workload_identity + ) + assert ( + sync_client.with_options(sts_base_url="https://other.example")._workload_identity + is not sync_client._workload_identity + ) + assert sync_client.with_options(api_key="key")._workload_identity is None + assert exchanges == 1 + + +@pytest.mark.parametrize( + "status,body", + [ + (400, {}), + (200, {"access_token": "secret"}), + (200, {"access_token": "secret", "token_type": "Bearer", "expires_in": 0}), + (302, {}), + ], +) +def test_failed_exchange_never_calls_api( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, status: int, body: dict[str, object] +) -> None: + monkeypatch.delenv("LIM_API_KEY", raising=False) + path = tmp_path / "identity.jwt" + path.write_text("external.jwt") + + def handle(request: httpx.Request) -> httpx.Response: + assert request.url.host == "sts.example.com" + return httpx.Response(status, json=body) + + with Limrun( + workload_token_file=str(path), + binding_id="binding_builds", + sts_base_url="https://sts.example.com", + http_client=httpx.Client(transport=httpx.MockTransport(handle)), + ) as client: + with pytest.raises(RuntimeError, match="[Ww]orkload token exchange") as error: + client.android_instances.list() + assert "external.jwt" not in str(error.value) + assert "secret" not in str(error.value) + + +@pytest.mark.parametrize("client_class", [Limrun, AsyncLimrun]) +@pytest.mark.parametrize("missing", ["binding_id", "workload_token_file"]) +def test_incomplete_identity_configuration( + monkeypatch: pytest.MonkeyPatch, client_class: type[Limrun] | type[AsyncLimrun], missing: str +) -> None: + for name in ( + "LIM_API_KEY", + "LIMRUN_WORKLOAD_IDENTITY_BINDING_ID", + "LIMRUN_WORKLOAD_IDENTITY_TOKEN", + "LIMRUN_WORKLOAD_IDENTITY_TOKEN_FILE", + ): + monkeypatch.delenv(name, raising=False) + message = "binding_id" if missing == "binding_id" else "workload_token, workload_token_file" + with pytest.raises(ValueError, match=f"Federation requires {message}"): + client_class( + binding_id=None if missing == "binding_id" else "binding_builds", + workload_token_file=None if missing == "workload_token_file" else "identity.jwt", + ) + + +@pytest.mark.parametrize("asynchronous", [False, True]) +async def test_api_key_bypasses_incomplete_identity_configuration( + monkeypatch: pytest.MonkeyPatch, asynchronous: bool +) -> None: + monkeypatch.setenv("LIMRUN_WORKLOAD_IDENTITY_TOKEN_FILE", "missing.jwt") + monkeypatch.delenv("LIMRUN_WORKLOAD_IDENTITY_BINDING_ID", raising=False) + if asynchronous: + async with AsyncLimrun(api_key="key") as client: + assert client._workload_identity is None + else: + with Limrun(api_key="key") as sync_client: + assert sync_client._workload_identity is None + + +def _subject_transport(subjects: list[str]) -> httpx.MockTransport: + """Records exchanged subject tokens and answers API calls with an empty list.""" + + def handle(request: httpx.Request) -> httpx.Response: + if request.url.host == "sts.example.com": + subjects.append(parse_qs(request.content.decode())["subject_token"][0]) + return httpx.Response( + 200, json={"access_token": "lim_st_session", "token_type": "Bearer", "expires_in": 300} + ) + assert request.headers["authorization"] == "Bearer lim_st_session" + return httpx.Response(200, json={"items": []}) + + return httpx.MockTransport(handle) + + +@pytest.fixture +def federation_env(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> Path: + for name in ( + "LIM_API_KEY", + "LIMRUN_WORKLOAD_IDENTITY_TOKEN", + "LIMRUN_WORKLOAD_IDENTITY_TOKEN_FILE", + "LIMRUN_WORKLOAD_IDENTITY_TOKEN_INJECTED", + ): + monkeypatch.delenv(name, raising=False) + monkeypatch.setenv("LIMRUN_WORKLOAD_IDENTITY_BINDING_ID", "binding_builds") + monkeypatch.setenv("LIMRUN_STS_BASE_URL", "https://sts.example.com") + path = tmp_path / "identity.jwt" + path.write_text("from-file") + return path + + +@pytest.mark.usefixtures("federation_env") +def test_sync_client_accepts_token_string_and_callable() -> None: + subjects: list[str] = [] + with Limrun( + workload_token=" from-string\n", http_client=httpx.Client(transport=_subject_transport(subjects)) + ) as client: + client.android_instances.list() + issued = iter(["jwt-1", "jwt-2"]) + with Limrun( + workload_token=lambda: next(issued), http_client=httpx.Client(transport=_subject_transport(subjects)) + ) as client: + client.android_instances.list() + assert client._workload_identity is not None + client._workload_identity.refresh_at = 0 + client.android_instances.list() + assert subjects == ["from-string", "jwt-1", "jwt-2"] + + +@pytest.mark.usefixtures("federation_env") +async def test_async_client_accepts_sync_and_async_callables() -> None: + subjects: list[str] = [] + + async def fetch_token() -> str: + return "async-jwt" + + for token in (fetch_token, lambda: "sync-jwt", "plain-jwt"): + async with AsyncLimrun( + workload_token=token, http_client=httpx.AsyncClient(transport=_subject_transport(subjects)) + ) as client: + await client.android_instances.list() + assert subjects == ["async-jwt", "sync-jwt", "plain-jwt"] + + +@pytest.mark.parametrize( + "explicit,env_token,env_file,expected", + [ + ({}, "env-jwt", False, "env-jwt"), + ({}, "env-jwt", True, "env-jwt"), + ({"workload_token": "explicit-jwt"}, "env-jwt", True, "explicit-jwt"), + ({"workload_token_file": True}, "env-jwt", False, "from-file"), + ({}, None, True, "from-file"), + ], +) +def test_identity_source_precedence( + federation_env: Path, + monkeypatch: pytest.MonkeyPatch, + explicit: dict[str, object], + env_token: str | None, + env_file: bool, + expected: str, +) -> None: + if env_token: + monkeypatch.setenv("LIMRUN_WORKLOAD_IDENTITY_TOKEN", env_token) + if env_file: + monkeypatch.setenv("LIMRUN_WORKLOAD_IDENTITY_TOKEN_FILE", str(federation_env)) + options = {k: (str(federation_env) if k == "workload_token_file" else v) for k, v in explicit.items()} + subjects: list[str] = [] + with Limrun(http_client=httpx.Client(transport=_subject_transport(subjects)), **options) as client: # type: ignore[arg-type] + client.android_instances.list() + assert subjects == [expected] + + +def test_copy_with_a_new_file_drops_the_current_token(federation_env: Path) -> None: + with Limrun(workload_token="from-string") as client: + copied = client.with_options(workload_token_file=str(federation_env)) + assert copied.workload_token is None + assert copied.workload_token_file == str(federation_env) + assert client.with_options(timeout=5)._workload_identity is client._workload_identity + + +@pytest.mark.usefixtures("federation_env") +def test_blank_token_is_refused_before_the_exchange() -> None: + def refuse(_: httpx.Request) -> httpx.Response: + raise AssertionError("exchange must not run") + + with Limrun(workload_token=lambda: " ", http_client=httpx.Client(transport=httpx.MockTransport(refuse))) as client: + with pytest.raises(ValueError, match="Workload identity token must be a JWT"): + client.android_instances.list() + + +def _injected_transport(forms: list[dict[str, list[str]]]) -> httpx.MockTransport: + def handle(request: httpx.Request) -> httpx.Response: + if request.url.host == "sts.example.com": + assert "authorization" not in request.headers + assert "x-limrun-subject-token" not in request.headers + forms.append(parse_qs(request.content.decode())) + return httpx.Response( + 200, json={"access_token": "lim_st_session", "token_type": "Bearer", "expires_in": 300} + ) + assert request.headers["authorization"] == "Bearer lim_st_session" + return httpx.Response(200, json={"items": []}) + + return httpx.MockTransport(handle) + + +@pytest.mark.parametrize("source", ["option", "environment"]) +@pytest.mark.usefixtures("federation_env") +async def test_injected_token_sends_no_subject(monkeypatch: pytest.MonkeyPatch, source: str) -> None: + if source == "environment": + monkeypatch.setenv("LIMRUN_WORKLOAD_IDENTITY_TOKEN_INJECTED", "true") + injected = True if source == "option" else None + forms: list[dict[str, list[str]]] = [] + with Limrun( + workload_token_injected=injected, http_client=httpx.Client(transport=_injected_transport(forms)) + ) as client: + client.android_instances.list() + async with AsyncLimrun( + workload_token_injected=injected, http_client=httpx.AsyncClient(transport=_injected_transport(forms)) + ) as async_client: + await async_client.android_instances.list() + assert len(forms) == 2 + for form in forms: + assert "subject_token" not in form + assert form["audience"] == ["binding_builds"] + + +@pytest.mark.parametrize("client_class", [Limrun, AsyncLimrun]) +@pytest.mark.parametrize("source", [{"workload_token": "jwt"}, {"workload_token_file": "identity.jwt"}]) +@pytest.mark.usefixtures("federation_env") +def test_injected_token_refuses_another_source( + client_class: type[Limrun] | type[AsyncLimrun], source: dict[str, str] +) -> None: + with pytest.raises(ValueError, match="workload_token_injected cannot be combined"): + client_class(workload_token_injected=True, **source) # type: ignore[arg-type] + + +@pytest.mark.usefixtures("federation_env") +def test_api_key_wins_over_conflicting_injected_configuration(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("LIMRUN_WORKLOAD_IDENTITY_TOKEN_INJECTED", "true") + monkeypatch.setenv("LIMRUN_WORKLOAD_IDENTITY_TOKEN", "jwt") + with Limrun(api_key="key") as client: + assert client._workload_identity is None + + +@pytest.mark.parametrize("client_class", [Limrun, AsyncLimrun]) +@pytest.mark.usefixtures("federation_env") +def test_copy_switches_identity_sources(client_class: type[Limrun] | type[AsyncLimrun]) -> None: + injected = client_class(workload_token_injected=True) + to_token = injected.with_options(workload_token="jwt") + assert (to_token.workload_token, to_token.workload_token_injected) == ("jwt", False) + to_file = injected.with_options(workload_token_file="identity.jwt") + assert (to_file.workload_token_file, to_file.workload_token_injected) == ("identity.jwt", False) + + token = client_class(workload_token="jwt") + to_injected = token.with_options(workload_token_injected=True) + assert (to_injected.workload_token, to_injected.workload_token_file) == (None, None) + assert to_injected.workload_token_injected is True + + unchanged = injected.with_options(timeout=5) + assert unchanged.workload_token_injected is True + assert unchanged._workload_identity is injected._workload_identity