From b4245aefafc07057f41e78c0b8d50fa572a89c68 Mon Sep 17 00:00:00 2001 From: "Garen J. Torikian" Date: Thu, 12 Nov 2026 01:18:08 -0800 Subject: [PATCH 01/24] feat(workload-identity): Add workload identity federation credentials A workload can now authenticate with a platform-issued JWT instead of a stored API key. Pass WorkloadIdentityCredentials as `credentials=` to WorkOSClient or AsyncWorkOSClient; the SDK exchanges the JWT for a short-lived access token (jwt-bearer grant), caches it on the credentials instance and refreshes it once less than min(60s, 20% of its lifetime) remains. Every client now authenticates through a credentials contract, resolved before each HTTP attempt. A static API key is the trivial implementation and its requests are unchanged. With workload identity the client also sends x-url-environment-id and, on a 401, discards that token generation, exchanges again and retries the request once. The exchange is shared by concurrent callers, bounded by a 30-second deadline, retried on transport failures, 429 and 5xx with the SDK's existing backoff, and never follows a redirect. OAuth errors surface as WorkloadIdentityError with a code, description and hint; neither token appears in an error. token_file and token_env providers are built in. Passing both api_key and credentials raises ValueError. Explicit credentials win over WORKOS_API_KEY, and a failing exchange never falls back to a key. No generated file is edited: the `credentials` keyword lives on the hand-maintained constructors in _base_client.py. Spec: docs/ideation/wif-backend-sdks/spec-phase-4.md --- src/workos/__init__.py | 15 + src/workos/_base_client.py | 129 ++- src/workos/_credentials.py | 108 ++ src/workos/workload_identity.py | 813 +++++++++++++++ tests/test_workload_identity.py | 1729 +++++++++++++++++++++++++++++++ 5 files changed, 2787 insertions(+), 7 deletions(-) create mode 100644 src/workos/_credentials.py create mode 100644 src/workos/workload_identity.py create mode 100644 tests/test_workload_identity.py diff --git a/src/workos/__init__.py b/src/workos/__init__.py index fc234f95..c9e7a88b 100644 --- a/src/workos/__init__.py +++ b/src/workos/__init__.py @@ -3,6 +3,7 @@ """WorkOS Python SDK.""" from ._client import AsyncWorkOSClient, WorkOSClient +from ._credentials import Credentials, CredentialSnapshot from ._errors import ( WorkOSError, AuthenticationError, @@ -30,6 +31,13 @@ ) from .public_client import create_public_client from ._types import NOT_GIVEN, NotGiven, RequestOptions +from .workload_identity import ( + IdentityTokenProvider, + WorkloadIdentityCredentials, + WorkloadIdentityError, + token_env, + token_file, +) __all__ = [ "WorkOSClient", @@ -59,4 +67,11 @@ "FeatureFlagsRuntimeClient", "AsyncFeatureFlagsRuntimeClient", "FeatureFlagsConfiguration", + "Credentials", + "CredentialSnapshot", + "WorkloadIdentityCredentials", + "IdentityTokenProvider", + "WorkloadIdentityError", + "token_file", + "token_env", ] diff --git a/src/workos/_base_client.py b/src/workos/_base_client.py index 3cfedc3f..ed03a95f 100644 --- a/src/workos/_base_client.py +++ b/src/workos/_base_client.py @@ -21,6 +21,12 @@ from typing_extensions import Self from ._types import _format_datetime +from ._credentials import ( + NO_CREDENTIALS, + Credentials, + StaticKeyCredentials, + apply_snapshot, +) from ._errors import ( APIError, WorkOSError, @@ -68,6 +74,11 @@ _INVALID_PATH_SEGMENTS = frozenset({"", ".", ".."}) +def _user_agent() -> str: + """The ``User-Agent`` every request from this SDK carries.""" + return f"WorkOS Python/{platform.python_version()} Python SDK/{VERSION}" + + def _parse_issuer_env(value: str) -> Optional[Union[str, List[str]]]: issuers = [issuer.strip() for issuer in value.split(",")] issuers = [issuer for issuer in issuers if issuer] @@ -90,16 +101,32 @@ def __init__( jwt_issuer: Optional[Union[str, Sequence[str]]] = None, max_retries: int = MAX_RETRIES, is_public: bool = False, + credentials: Optional[Credentials] = None, ) -> None: + if credentials is not None: + if api_key: + raise ValueError( + "WorkOS accepts either api_key or credentials, not both. " + "Remove api_key to authenticate with the credentials object." + ) + if is_public: + raise ValueError( + "A public client sends no credentials. " + "Remove credentials, or do not set is_public." + ) self._is_public = is_public + self._credentials = credentials # Public clients (PKCE / browser / mobile / CLI) must never attach # an API key, even if WORKOS_API_KEY is present in the environment. - if is_public: + # Neither must a client built with credentials: explicit credentials + # win over the environment, and a failing credentials object never + # falls back to a key. + if is_public or credentials is not None: self._api_key: Optional[str] = None else: self._api_key = api_key or os.environ.get("WORKOS_API_KEY") self.client_id = client_id or os.environ.get("WORKOS_CLIENT_ID") - if not self._api_key and not self.client_id: + if not self._api_key and not self.client_id and credentials is None: raise ValueError( "WorkOS requires either an API key or a client ID. " "Provide api_key / WORKOS_API_KEY for authenticated server-side usage, " @@ -325,6 +352,28 @@ def _require_client_id(self) -> str: ) return self.client_id + def _request_credentials( + self, request_options: Optional[RequestOptions] + ) -> Credentials: + """The credentials that authenticate one logical request. + + A credentials object passed to the client always applies: its headers + overwrite any ``Authorization`` header on the request. With a static + API key, an ``Authorization`` header passed in ``extra_headers`` has + always won over the key, and still does. + """ + if self._credentials is not None: + return self._credentials + if request_options: + extra = request_options.get("extra_headers") + if isinstance(extra, dict) and any( + str(name).lower() == "authorization" + for name in cast(Dict[str, str], extra) + ): + return NO_CREDENTIALS + # Built per request so it follows the client's current API key. + return StaticKeyCredentials(self._api_key) + def _build_headers( self, method: str, @@ -333,7 +382,7 @@ def _build_headers( ) -> Dict[str, str]: headers: Dict[str, str] = { "Content-Type": "application/json", - "User-Agent": f"WorkOS Python/{platform.python_version()} Python SDK/{VERSION}", + "User-Agent": _user_agent(), } if self._api_key: headers["Authorization"] = f"Bearer {self._api_key}" @@ -500,6 +549,7 @@ def __init__( max_retries: int = MAX_RETRIES, is_public: bool = False, http_client: Optional[SyncHTTPClient] = None, + credentials: Optional[Credentials] = None, ) -> None: """Initialize the WorkOS client. @@ -522,9 +572,15 @@ def __init__( :class:`workos.HTTPBackend`. Defaults to a new ``httpx2.Client`` that this instance owns and closes. A client you pass in is never closed by the SDK. + credentials: Credentials to authenticate with instead of an API key, + such as :class:`workos.WorkloadIdentityCredentials`. They are + resolved before every HTTP attempt. ``WORKOS_API_KEY`` is + ignored when credentials are passed. Raises: - ValueError: If neither api_key nor client_id is provided, directly or via environment variables. + ValueError: If neither api_key, client_id nor credentials is provided, + directly or via environment variables; or if credentials are + passed together with api_key or is_public. TypeError: If ``http_client`` is not a supported client type. """ super().__init__( @@ -536,6 +592,7 @@ def __init__( jwt_issuer=jwt_issuer, max_retries=max_retries, is_public=is_public, + credentials=credentials, ) self._backend, self._owns_http_client = resolve_sync_backend( http_client, self._request_timeout @@ -602,19 +659,44 @@ def request( content = self._encode_body(body) timeout = self._resolve_timeout(request_options) max_retries = self._resolve_max_retries(request_options) + credentials = self._request_credentials(request_options) + # One 401 recovery per logical request. Set once, never cleared, however + # many transport retries follow. + recovery_used = False last_error: Optional[Exception] = None if self._first_request_pid is None: self._first_request_pid = os.getpid() record_request(self._backend) for attempt in range(max_retries + 1): try: + # Resolved before every attempt, so a retry never sends a token + # that expired while the request was backing off. + snapshot = credentials.resolve(timeout=timeout) response = self._backend.request( method.upper(), url, - headers=headers, + headers=apply_snapshot(headers, snapshot), content=content, timeout=timeout, ) + if ( + response.status_code == 401 + and snapshot.recoverable + and not recovery_used + ): + # The API rejected this token. Discard that generation and + # resend once, with the same body and idempotency key and + # no backoff. Whatever comes back is handled as usual. + recovery_used = True + credentials.invalidate(snapshot.generation) + snapshot = credentials.resolve(timeout=timeout) + response = self._backend.request( + method.upper(), + url, + headers=apply_snapshot(headers, snapshot), + content=content, + timeout=timeout, + ) if response.status_code in RETRY_STATUS_CODES and attempt < max_retries: delay = self._calculate_retry_delay( attempt, response.headers.get("Retry-After") @@ -755,6 +837,7 @@ def __init__( max_retries: int = MAX_RETRIES, is_public: bool = False, http_client: Optional[AsyncHTTPClient] = None, + credentials: Optional[Credentials] = None, ) -> None: """Initialize the async WorkOS client. @@ -773,9 +856,15 @@ def __init__( implementing :class:`workos.AsyncHTTPBackend`. Defaults to a new ``httpx2.AsyncClient`` that this instance owns and closes. A client you pass in is never closed by the SDK. + credentials: Credentials to authenticate with instead of an API key, + such as :class:`workos.WorkloadIdentityCredentials`. They are + resolved before every HTTP attempt. ``WORKOS_API_KEY`` is + ignored when credentials are passed. Raises: - ValueError: If neither api_key nor client_id is provided, directly or via environment variables. + ValueError: If neither api_key, client_id nor credentials is provided, + directly or via environment variables; or if credentials are + passed together with api_key or is_public. TypeError: If ``http_client`` is not a supported client type. """ super().__init__( @@ -787,6 +876,7 @@ def __init__( jwt_issuer=jwt_issuer, max_retries=max_retries, is_public=is_public, + credentials=credentials, ) self._backend, self._owns_http_client = resolve_async_backend( http_client, self._request_timeout @@ -853,19 +943,44 @@ async def request( content = self._encode_body(body) timeout = self._resolve_timeout(request_options) max_retries = self._resolve_max_retries(request_options) + credentials = self._request_credentials(request_options) + # One 401 recovery per logical request. Set once, never cleared, however + # many transport retries follow. + recovery_used = False last_error: Optional[Exception] = None if self._first_request_pid is None: self._first_request_pid = os.getpid() record_request(self._backend) for attempt in range(max_retries + 1): try: + # Resolved before every attempt, so a retry never sends a token + # that expired while the request was backing off. + snapshot = await credentials.aresolve(timeout=timeout) response = await self._backend.request( method.upper(), url, - headers=headers, + headers=apply_snapshot(headers, snapshot), content=content, timeout=timeout, ) + if ( + response.status_code == 401 + and snapshot.recoverable + and not recovery_used + ): + # The API rejected this token. Discard that generation and + # resend once, with the same body and idempotency key and + # no backoff. Whatever comes back is handled as usual. + recovery_used = True + credentials.invalidate(snapshot.generation) + snapshot = await credentials.aresolve(timeout=timeout) + response = await self._backend.request( + method.upper(), + url, + headers=apply_snapshot(headers, snapshot), + content=content, + timeout=timeout, + ) if response.status_code in RETRY_STATUS_CODES and attempt < max_retries: delay = self._calculate_retry_delay( attempt, response.headers.get("Retry-After") diff --git a/src/workos/_credentials.py b/src/workos/_credentials.py new file mode 100644 index 00000000..1d154040 --- /dev/null +++ b/src/workos/_credentials.py @@ -0,0 +1,108 @@ +# @oagen-ignore-file +# This file is hand-maintained. The credentials contract every WorkOS client +# authenticates through, and its static API key implementation. + +"""How a WorkOS client gets the authorization headers for a request. + +A client resolves a :class:`CredentialSnapshot` before every HTTP attempt. A +static API key is the trivial implementation; workload identity federation +(:mod:`workos.workload_identity`) is the other. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Dict, Mapping, Optional, Protocol + + +@dataclass(frozen=True) +class CredentialSnapshot: + """The authorization headers for one HTTP attempt. + + Attributes: + headers: Headers to set on the attempt. They hold a bearer token, so + they are left out of ``repr()``. + generation: Identifies the credential the headers came from. A 401 + invalidates this generation, never a newer one. + recoverable: True when a 401 on this snapshot is worth one re-resolve. + """ + + headers: Mapping[str, str] = field(repr=False) + generation: int + recoverable: bool + + +class Credentials(Protocol): + """Source of authorization headers for a WorkOS client. + + Pass an implementation as ``credentials=`` to :class:`workos.WorkOSClient` + or :class:`workos.AsyncWorkOSClient`. The synchronous client calls + :meth:`resolve`; the asynchronous client awaits :meth:`aresolve`. + """ + + def resolve(self, *, timeout: Optional[float] = None) -> CredentialSnapshot: + """Return the headers for the next HTTP attempt. + + May block. ``timeout`` is how long, in seconds, the caller is prepared + to wait. + """ + ... + + async def aresolve(self, *, timeout: Optional[float] = None) -> CredentialSnapshot: + """Asynchronous twin of :meth:`resolve`.""" + ... + + def invalidate(self, generation: int) -> None: + """Discard the credential of ``generation`` after the API rejected it. + + Never blocks on the network. Does nothing when a newer generation is + already current. + """ + ... + + +class StaticKeyCredentials: + """Credentials for a static API key: one snapshot that never changes.""" + + def __init__(self, api_key: Optional[str]) -> None: + headers: Dict[str, str] = ( + {"Authorization": f"Bearer {api_key}"} if api_key else {} + ) + self._snapshot = CredentialSnapshot( + headers=headers, generation=0, recoverable=False + ) + + def resolve(self, *, timeout: Optional[float] = None) -> CredentialSnapshot: + return self._snapshot + + async def aresolve(self, *, timeout: Optional[float] = None) -> CredentialSnapshot: + return self._snapshot + + def invalidate(self, generation: int) -> None: + return None + + +# Used for a request whose own ``Authorization`` header overrides a static API +# key: nothing to add, nothing to recover. +NO_CREDENTIALS = StaticKeyCredentials(None) + + +def apply_snapshot( + headers: Dict[str, str], snapshot: CredentialSnapshot +) -> Dict[str, str]: + """Return ``headers`` with the snapshot's headers set on top. + + A snapshot header replaces a header of the same name whatever its case, so + a request never carries two ``Authorization`` headers. A header that is + already spelled the same way keeps its position. + """ + if not snapshot.headers: + return headers + merged = dict(headers) + for name, value in snapshot.headers.items(): + lowered = name.lower() + for existing in [key for key in merged if key.lower() == lowered]: + if existing != name: + del merged[existing] + merged[name] = value + return merged diff --git a/src/workos/workload_identity.py b/src/workos/workload_identity.py new file mode 100644 index 00000000..b08c10d8 --- /dev/null +++ b/src/workos/workload_identity.py @@ -0,0 +1,813 @@ +# @oagen-ignore-file +# This file is hand-maintained. Workload identity federation: a workload +# exchanges a JWT issued by its platform for a short-lived WorkOS access token, +# so it needs no stored API key. + +"""Workload identity federation (WIF) credentials for the WorkOS client. + +Build a :class:`WorkloadIdentityCredentials` and pass it as ``credentials=`` to +:class:`workos.WorkOSClient` or :class:`workos.AsyncWorkOSClient`:: + + from workos import WorkOSClient, WorkloadIdentityCredentials, token_file + + client = WorkOSClient( + credentials=WorkloadIdentityCredentials( + client_id="client_...", + token_url="https://.../oauth2/token", + environment_id="environment_...", + identity_token_provider=token_file("/var/run/secrets/tokens/workos"), + ) + ) + +The identity token provider is any callable that returns the workload's JWT. +:func:`token_file` and :func:`token_env` are built in; the GitHub Actions, GCP +and AWS providers are separate distributions. +""" + +from __future__ import annotations + +import asyncio +import inspect +import math +import os +import threading +import time +from typing import ( + Any, + Awaitable, + Callable, + Dict, + Optional, + Protocol, + Tuple, + Union, + cast, +) +from urllib.parse import urlencode + +import httpx2 + +from ._base_client import MAX_RETRIES, _BaseWorkOSClient, _user_agent +from ._credentials import CredentialSnapshot +from ._errors import WorkOSError, WorkOSTimeoutError +from ._http import AsyncHttpxBackend, HTTPResponse, HttpxBackend, TransportError + +__all__ = [ + "ENVIRONMENT_ID_HEADER", + "IdentityTokenProvider", + "WorkloadIdentityCredentials", + "WorkloadIdentityError", + "token_env", + "token_file", +] + +# --- constants ------------------------------------------------------------------ + +# Sent on every API request made with workload identity credentials. +ENVIRONMENT_ID_HEADER = "x-url-environment-id" +GRANT_TYPE = "urn:ietf:params:oauth:grant-type:jwt-bearer" +DEFAULT_RESOURCE = "https://api.workos.com" +# A token is refreshed once less than min(60 seconds, 20% of its lifetime) is left. +REFRESH_THRESHOLD_SECONDS = 60.0 +REFRESH_THRESHOLD_FRACTION = 0.2 +# Used when the token response has no usable ``expires_in``. +DEFAULT_LIFETIME_SECONDS = 300.0 +# The whole exchange, including retries and backoff. +EXCHANGE_DEADLINE_SECONDS = 30.0 +DESCRIPTION_LIMIT = 500 + +_CLIENT_ID_ENV = "WORKOS_CLIENT_ID" +_TOKEN_URL_ENV = "WORKOS_WIF_TOKEN_URL" +_SCOPE_ENV = "WORKOS_WIF_SCOPE" +_ENVIRONMENT_ID_ENV = "WORKOS_ENVIRONMENT_ID" + +# How long past its deadline a synchronous exchange may run before a waiter +# gives it up for lost. See WorkloadIdentityCredentials._wait. +_DEADLINE_GRACE_SECONDS = 1.0 +_DEADLINE_DESCRIPTION = ( + f"The exchange did not finish within {EXCHANGE_DEADLINE_SECONDS:g} seconds." +) +_WAIT_TIMEOUT_MESSAGE = "Timed out waiting for the workload identity token exchange." + +# --- errors --------------------------------------------------------------------- + +# One sentence per error code. The wording is pending the server's final error +# codes; keep every hint in this table so a change is made in one place. +_HINTS: Dict[str, str] = { + # OAuth error codes from the token endpoint. + "invalid_grant": ( + "The identity token did not match a trust rule for this application, " + "or the token has expired. Check the issuer, audience and subject " + "claims against the trust rule." + ), + "invalid_target": ( + "The resource or audience is wrong. The trust rule's audience must " + "match the audience the identity token was requested with, and the " + "resource must be registered for the environment." + ), + "invalid_client": ( + "Check that the client ID is the M2M application that has the trust rule." + ), + "unauthorized_client": ( + "This application is not allowed to use workload identity federation. " + "Check that the feature is enabled for the environment and that the " + "application has a trust rule." + ), + "invalid_scope": ( + "The requested scope is not allowed for this application. Fix the " + "scope or leave it unset." + ), + "invalid_request": ( + "The token request was malformed. Check that the token URL points at " + "the `/oauth2/token` endpoint." + ), + # Codes the SDK sets for failures that have no OAuth code. + "exchange_failed": ( + "The token endpoint could not be reached or kept failing. Check the " + "token URL and try again." + ), + "invalid_response": ( + "The token endpoint returned a response the SDK could not read. Check " + "that the token URL points at the `/oauth2/token` endpoint." + ), + "provider_failed": ( + "The identity token provider failed, so there was no token to exchange." + ), + "invalid_configuration": ( + "Workload identity credentials are missing a required setting." + ), +} +_OTHER_OAUTH_HINT = "The token endpoint rejected the exchange." + + +class WorkloadIdentityError(WorkOSError): + """A workload identity token could not be obtained. + + Attributes: + code: The OAuth error code from the token endpoint, or one of the SDK's + own codes: ``exchange_failed``, ``invalid_response``, + ``provider_failed``, ``invalid_configuration``. + description: The server's ``error_description`` (at most 500 + characters), or detail from the SDK. May be empty. + hint: One sentence on what to check. Never empty. + + The message is ``: ``, followed by the description when there + is one. It never contains the identity token or the access token. + """ + + code: str + description: str + hint: str + + def __init__(self, code: str, description: str = "") -> None: + self.code = code + self.description = description[:DESCRIPTION_LIMIT] + self.hint = _HINTS.get(code, _OTHER_OAUTH_HINT) + message = f"{code}: {self.hint}" + if self.description: + message = f"{message} {self.description}" + super().__init__(message) + + +# --- providers ------------------------------------------------------------------ + + +class IdentityTokenProvider(Protocol): + """A callable that returns the workload's JWT. + + Called once per exchange attempt; it may return the same token each time. + A plain function may block: the asynchronous client runs it in a worker + thread. A coroutine function is awaited (asynchronous client only). + """ + + def __call__(self) -> Union[str, Awaitable[str]]: ... + + +def token_file(path: Union[str, "os.PathLike[str]"]) -> IdentityTokenProvider: + """Return a provider that reads the identity token from a file. + + The file is read on every exchange, so a rotated token is picked up, and + surrounding whitespace is trimmed. A missing or empty file is an error. + """ + + def provider() -> str: + with open(path, "r", encoding="utf-8") as handle: + token = handle.read().strip() + if not token: + raise ValueError(f"The identity token file is empty: {os.fspath(path)}") + return token + + return provider + + +def token_env(name: str) -> IdentityTokenProvider: + """Return a provider that reads the identity token from an environment variable. + + The variable is read on every exchange. An unset or empty variable is an + error. + """ + + def provider() -> str: + token = os.environ.get(name, "") + if not token: + raise ValueError(f"The environment variable {name} is unset or empty.") + return token + + return provider + + +class _AsyncProviderInSyncClient(Exception): + """A provider returned an awaitable where there is no event loop to await it.""" + + +def _is_coroutine_callable(provider: object) -> bool: + return inspect.iscoroutinefunction(provider) or inspect.iscoroutinefunction( + getattr(provider, "__call__", None) + ) + + +def _require_token(value: object) -> str: + if not isinstance(value, str): + raise TypeError( + f"The identity token provider returned {type(value).__name__}, not a string." + ) + if not value: + raise ValueError("The identity token provider returned an empty token.") + return value + + +# --- exchange ------------------------------------------------------------------- + + +def _redact(text: str, secret: str) -> str: + return text.replace(secret, "[redacted]") if secret else text + + +def _lifetime(expires_in: object) -> float: + """``expires_in`` in seconds, or the default when absent, not a number or not positive.""" + if isinstance(expires_in, bool) or not isinstance(expires_in, (int, float)): + return DEFAULT_LIFETIME_SECONDS + lifetime = float(expires_in) + if not math.isfinite(lifetime) or lifetime <= 0: + return DEFAULT_LIFETIME_SECONDS + return lifetime + + +def _json_object(response: HTTPResponse) -> Optional[Dict[str, Any]]: + try: + data = response.json() + except (ValueError, RecursionError): + return None + return cast(Dict[str, Any], data) if isinstance(data, dict) else None + + +def _exchange_headers() -> Dict[str, str]: + # No Authorization header: the exchange carries no client secret and no API key. + return { + "Content-Type": "application/x-www-form-urlencoded", + "Accept": "application/json", + "User-Agent": _user_agent(), + } + + +class _ExchangeRun: + """State of one exchange across its attempts, shared by the sync and async loops.""" + + def __init__(self, deadline: float) -> None: + self._deadline = deadline + self._code = "exchange_failed" + self._description = "" + self._cause: Optional[BaseException] = None + self._retry_after: Optional[str] = None + + def remaining(self) -> float: + """Seconds left before the deadline. Raises when there are none.""" + remaining = self._deadline - time.monotonic() + if remaining <= 0: + raise WorkloadIdentityError("exchange_failed", _DEADLINE_DESCRIPTION) + return remaining + + def attempt_timeout(self, attempt: int) -> float: + """The HTTP timeout for ``attempt``: an even share of the time left. + + One attempt given the whole deadline would leave nothing to retry a + timeout with. + """ + return self.remaining() / (MAX_RETRIES + 1 - attempt) + + def backoff(self, attempt: int) -> float: + """Seconds to sleep before ``attempt``, from the SDK's own retry policy.""" + delay = _BaseWorkOSClient._calculate_retry_delay(attempt - 1, self._retry_after) + self._retry_after = None + if delay >= self._deadline - time.monotonic(): + # The next attempt could not start in time; report the last failure. + raise self.exhausted() + return delay + + def provider_failed(self, error: Exception) -> None: + self._code = "provider_failed" + self._description = str(error) or type(error).__name__ + self._cause = error + + def transport_failed(self, error: TransportError) -> None: + # Only the kind of failure: never the request, which holds the assertion. + self._code = "exchange_failed" + self._description = ( + f"The request to the token endpoint failed ({type(error).__name__})." + ) + self._cause = None + + def exhausted(self) -> WorkloadIdentityError: + """The error for an exchange whose every attempt failed.""" + error = WorkloadIdentityError(self._code, self._description) + error.__cause__ = self._cause + return error + + def read( + self, response: HTTPResponse, assertion: str + ) -> Optional[Tuple[str, float]]: + """Return ``(access_token, lifetime)``, or None to retry. Raises when terminal. + + The status is checked before the body: a 429 or 5xx is retried even when + its body carries an OAuth error; an OAuth error on any other status is + terminal. + """ + status = response.status_code + body = _json_object(response) + error = body.get("error") if body is not None else None + oauth_code = ( + _redact(error, assertion) if isinstance(error, str) and error else "" + ) + detail = body.get("error_description") if body is not None else None + oauth_description = ( + _redact(detail, assertion) if isinstance(detail, str) else "" + ) + + if status == 429 or 500 <= status <= 599: + self._code = oauth_code or "exchange_failed" + self._description = ( + oauth_description or f"The token endpoint returned HTTP {status}." + ) + self._cause = None + self._retry_after = response.headers.get("Retry-After") + return None + if oauth_code: + raise WorkloadIdentityError(oauth_code, oauth_description) + if 300 <= status <= 399: + raise WorkloadIdentityError( + "exchange_failed", + f"The token endpoint returned HTTP {status}; redirects are not followed.", + ) + if status != 200: + raise WorkloadIdentityError( + "invalid_response", f"The token endpoint returned HTTP {status}." + ) + if body is None: + raise WorkloadIdentityError( + "invalid_response", "The response body is not a JSON object." + ) + access_token = body.get("access_token") + if not isinstance(access_token, str) or not access_token: + raise WorkloadIdentityError( + "invalid_response", "The response has no access_token." + ) + return access_token, _lifetime(body.get("expires_in")) + + +class _SyncExchange: + """One in-flight exchange started by the synchronous path, and its shared result.""" + + __slots__ = ("deadline", "done", "error", "result", "settled") + + def __init__(self, deadline: float) -> None: + self.deadline = deadline + self.done = threading.Event() + self.settled = False + self.result: Optional[Tuple[str, int]] = None + self.error: Optional[BaseException] = None + + def outcome(self) -> Tuple[str, int]: + if self.error is not None: + raise self.error + assert self.result is not None + return self.result + + +def _retrieve_exception(task: "asyncio.Task[Tuple[str, int]]") -> None: + # Marks a failed exchange's exception as seen, so asyncio does not log + # "Task exception was never retrieved" when every waiter has given up. + if not task.cancelled(): + task.exception() + + +# --- credentials ---------------------------------------------------------------- + + +class WorkloadIdentityCredentials: + """Credentials that exchange a workload's JWT for a WorkOS access token. + + The access token is cached on this instance, in memory only, and refreshed + on demand once less than ``min(60 seconds, 20% of its lifetime)`` remains. + Concurrent callers share one exchange. Two instances never share a token, + even with identical settings. + + Settings are fixed at construction; build a new instance to change one. An + omitted setting falls back to its environment variable. The environment + variables never switch workload identity on by themselves. + + Args: + identity_token_provider: A callable returning the workload's JWT, such + as :func:`token_file`, :func:`token_env`, a platform provider, or + your own function. + client_id: The M2M application's client ID. Falls back to + ``WORKOS_CLIENT_ID``. + token_url: The token exchange endpoint. Falls back to + ``WORKOS_WIF_TOKEN_URL``. There is no built-in default. + environment_id: The environment ID, sent as a header on every API + request. Falls back to ``WORKOS_ENVIRONMENT_ID``. + resource: The ``resource`` to request a token for. Defaults to + ``https://api.workos.com``. + scope: The ``scope`` to request. Falls back to ``WORKOS_WIF_SCOPE``; + left out of the request when empty. + + Raises: + WorkloadIdentityError: With code ``invalid_configuration`` when a + required setting is missing after the environment is consulted. + """ + + def __init__( + self, + *, + identity_token_provider: IdentityTokenProvider, + client_id: Optional[str] = None, + token_url: Optional[str] = None, + environment_id: Optional[str] = None, + resource: Optional[str] = None, + scope: Optional[str] = None, + ) -> None: + if not callable(identity_token_provider): + raise WorkloadIdentityError( + "invalid_configuration", + "identity_token_provider is required and must be callable", + ) + self._provider = identity_token_provider + self._client_id = self._required("client_id", client_id, _CLIENT_ID_ENV) + self._token_url = self._required("token_url", token_url, _TOKEN_URL_ENV) + self._environment_id = self._required( + "environment_id", environment_id, _ENVIRONMENT_ID_ENV + ) + self._resource = resource or DEFAULT_RESOURCE + self._scope = scope or os.environ.get(_SCOPE_ENV) or None + + # The cache. Guarded by _lock, which is held only for these few fields + # and never across I/O, so both the sync and the async path may take it. + self._lock = threading.Lock() + self._token: Optional[str] = None + self._expires_at = -math.inf + self._lifetime = 0.0 + self._generation = 0 + # In-flight exchanges. The two kinds of client wait in different ways, + # so each has its own: a thread for sync callers, a task for async ones. + self._inflight: Optional[_SyncExchange] = None + self._async_inflight: Optional["asyncio.Task[Tuple[str, int]]"] = None + + # Seams for tests: the clock that decides freshness, and the sleeps + # between exchange attempts. + self._clock: Callable[[], float] = time.monotonic + self._sleep: Callable[[float], None] = time.sleep + self._async_sleep: Callable[[float], Awaitable[None]] = asyncio.sleep + + @staticmethod + def _required(field: str, value: Optional[str], env: str) -> str: + resolved = value or os.environ.get(env) + if not resolved: + raise WorkloadIdentityError( + "invalid_configuration", f"{field} is required (or set {env})" + ) + return resolved + + @property + def client_id(self) -> str: + """The M2M application's client ID.""" + return self._client_id + + @property + def token_url(self) -> str: + """The token exchange endpoint.""" + return self._token_url + + @property + def environment_id(self) -> str: + """The environment ID sent with every API request.""" + return self._environment_id + + @property + def resource(self) -> str: + """The resource a token is requested for.""" + return self._resource + + @property + def scope(self) -> Optional[str]: + """The scope requested, or None when no scope is sent.""" + return self._scope + + def __repr__(self) -> str: + return ( + f"{type(self).__name__}(client_id={self._client_id!r}, " + f"token_url={self._token_url!r}, environment_id={self._environment_id!r})" + ) + + # --- the credentials contract --- + + def resolve(self, *, timeout: Optional[float] = None) -> CredentialSnapshot: + """Return headers carrying a fresh access token, exchanging if needed. + + Blocks while an exchange runs, for at most ``timeout`` seconds. A caller + that times out stops waiting; the exchange carries on for the others. + + Raises: + WorkloadIdentityError: The exchange failed. + WorkOSTimeoutError: ``timeout`` passed before the exchange finished. + """ + with self._lock: + current = self._fresh() + exchange = None if current is not None else self._join_or_start() + if exchange is not None: + current = self._wait(exchange, timeout) + assert current is not None + return self._snapshot(*current) + + async def aresolve(self, *, timeout: Optional[float] = None) -> CredentialSnapshot: + """Asynchronous twin of :meth:`resolve`. + + Canceling the awaiting task, or its ``timeout`` passing, stops that + caller waiting. The shared exchange carries on for the others. + """ + with self._lock: + current = self._fresh() + if current is None: + task = self._join_or_start_async() + try: + current = await asyncio.wait_for(asyncio.shield(task), timeout) + except asyncio.TimeoutError: + raise WorkOSTimeoutError(_WAIT_TIMEOUT_MESSAGE) from None + return self._snapshot(*current) + + def invalidate(self, generation: int) -> None: + """Discard the cached token if it is still the one of ``generation``. + + A late 401 for an old token leaves a newer token in place. + """ + with self._lock: + if self._generation == generation: + self._expires_at = -math.inf + + # --- cache --- + + def _snapshot(self, token: str, generation: int) -> CredentialSnapshot: + return CredentialSnapshot( + headers={ + "Authorization": f"Bearer {token}", + ENVIRONMENT_ID_HEADER: self._environment_id, + }, + generation=generation, + recoverable=True, + ) + + def _fresh(self) -> Optional[Tuple[str, int]]: + """The cached token and its generation, if it is not due a refresh. Lock held.""" + if self._token is None: + return None + threshold = min( + REFRESH_THRESHOLD_SECONDS, REFRESH_THRESHOLD_FRACTION * self._lifetime + ) + if self._expires_at - self._clock() < threshold: + return None + return self._token, self._generation + + def _store(self, token: str, lifetime: float) -> int: + """Cache a new token and return its generation. Lock held.""" + self._token = token + self._lifetime = lifetime + self._expires_at = self._clock() + lifetime + self._generation += 1 + return self._generation + + # --- shared exchange, synchronous callers --- + + def _join_or_start(self) -> _SyncExchange: + """The exchange in progress, started if there is none. Lock held.""" + exchange = self._inflight + if exchange is None: + exchange = _SyncExchange(time.monotonic() + EXCHANGE_DEADLINE_SECONDS) + self._inflight = exchange + try: + # Its own thread, not the first caller's: a caller that gives up + # must not take the exchange down with it. + threading.Thread( + target=self._run_exchange, + args=(exchange,), + name="workos-workload-identity-exchange", + daemon=True, + ).start() + except BaseException: + self._inflight = None + raise + return exchange + + def _run_exchange(self, exchange: _SyncExchange) -> None: + try: + token, lifetime = self._exchange(exchange.deadline) + except BaseException as error: + self._settle(exchange, error=error) + return + self._settle(exchange, token=token, lifetime=lifetime) + + def _settle( + self, + exchange: _SyncExchange, + *, + token: Optional[str] = None, + lifetime: float = 0.0, + error: Optional[BaseException] = None, + ) -> None: + """Record an exchange's outcome, clear it as in-flight, then wake its waiters. + + The in-flight slot is cleared before anyone is woken, so a caller that + gets an error and calls again starts a new exchange. On success the + token is stored under the same lock that clears the slot. + """ + with self._lock: + generation = self._store(token, lifetime) if token is not None else 0 + if self._inflight is exchange: + self._inflight = None + if exchange.settled: + # A waiter already gave this exchange up at its deadline. + return + exchange.settled = True + if token is not None: + exchange.result = (token, generation) + else: + exchange.error = error + exchange.done.set() + + def _wait( + self, exchange: _SyncExchange, timeout: Optional[float] + ) -> Tuple[str, int]: + overdue_at = exchange.deadline + _DEADLINE_GRACE_SECONDS + budget = overdue_at - time.monotonic() + patience = budget if timeout is None else min(timeout, budget) + if exchange.done.wait(max(patience, 0.0)): + return exchange.outcome() + if time.monotonic() < overdue_at: + # This caller's own timeout. The exchange is left alone. + raise WorkOSTimeoutError(_WAIT_TIMEOUT_MESSAGE) + # The exchange outran its deadline, which only a provider that does not + # return can cause: a thread cannot be interrupted. Give it up so the + # next caller starts a new exchange instead of waiting on this one. + self._settle( + exchange, + error=WorkloadIdentityError("exchange_failed", _DEADLINE_DESCRIPTION), + ) + exchange.done.wait() + return exchange.outcome() + + # --- shared exchange, asynchronous callers --- + + def _join_or_start_async(self) -> "asyncio.Task[Tuple[str, int]]": + loop = asyncio.get_running_loop() + with self._lock: + task = self._async_inflight + # A task is bound to its event loop; one left by another loop, or + # canceled before it ever ran, cannot be joined. + if task is None or task.done() or task.get_loop() is not loop: + task = loop.create_task(self._run_exchange_async()) + task.add_done_callback(_retrieve_exception) + self._async_inflight = task + return task + + async def _run_exchange_async(self) -> Tuple[str, int]: + task = asyncio.current_task() + deadline = time.monotonic() + EXCHANGE_DEADLINE_SECONDS + try: + try: + token, lifetime = await asyncio.wait_for( + self._exchange_async(deadline), EXCHANGE_DEADLINE_SECONDS + ) + except asyncio.TimeoutError: + raise WorkloadIdentityError( + "exchange_failed", _DEADLINE_DESCRIPTION + ) from None + with self._lock: + generation = self._store(token, lifetime) + if self._async_inflight is task: + self._async_inflight = None + return token, generation + finally: + # Cleared on every path, before any waiter sees the outcome. + with self._lock: + if self._async_inflight is task: + self._async_inflight = None + + # --- the exchange itself --- + + def _form(self, assertion: str) -> bytes: + fields = { + "grant_type": GRANT_TYPE, + "assertion": assertion, + "client_id": self._client_id, + "resource": self._resource, + } + if self._scope: + fields["scope"] = self._scope + return urlencode(fields).encode("ascii") + + def _provide(self) -> str: + result = self._provider() + if inspect.isawaitable(result): + if inspect.iscoroutine(result): + result.close() + raise _AsyncProviderInSyncClient( + "The identity token provider is asynchronous. Use it with " + "AsyncWorkOSClient, or pass a synchronous provider." + ) + return _require_token(result) + + async def _provide_async(self) -> str: + provider = self._provider + if _is_coroutine_callable(provider): + result: object = await cast(Awaitable[str], provider()) + else: + # A plain callable may block (a file read, a cloud SDK call), so it + # runs in a worker thread and cannot stall the event loop. + result = await asyncio.to_thread(provider) + if inspect.isawaitable(result): + result = await result + return _require_token(result) + + def _exchange(self, deadline: float) -> Tuple[str, float]: + """Exchange the identity token, retrying per the SDK's retry policy. + + Retried: a provider failure, a transport failure, HTTP 429 and 5xx. The + provider is called again and the form rebuilt on every attempt. + """ + run = _ExchangeRun(deadline) + # A client of its own: redirects are never followed, and nothing a + # caller installed on the API client (hooks, auth, logging) sees the + # assertion or the token. + with httpx2.Client(follow_redirects=False) as http: + backend = HttpxBackend(http) + for attempt in range(MAX_RETRIES + 1): + if attempt > 0: + self._sleep(run.backoff(attempt)) + try: + assertion = self._provide() + except _AsyncProviderInSyncClient as error: + raise WorkloadIdentityError("provider_failed", str(error)) from None + except Exception as error: + run.provider_failed(error) + continue + try: + response = backend.request( + "POST", + self._token_url, + headers=_exchange_headers(), + content=self._form(assertion), + timeout=run.attempt_timeout(attempt), + ) + except TransportError as error: + run.transport_failed(error) + continue + result = run.read(response, assertion) + if result is not None: + return result + raise run.exhausted() + + async def _exchange_async(self, deadline: float) -> Tuple[str, float]: + """Asynchronous twin of :meth:`_exchange`.""" + run = _ExchangeRun(deadline) + async with httpx2.AsyncClient(follow_redirects=False) as http: + backend = AsyncHttpxBackend(http) + for attempt in range(MAX_RETRIES + 1): + if attempt > 0: + await self._async_sleep(run.backoff(attempt)) + try: + assertion = await self._provide_async() + except Exception as error: + run.provider_failed(error) + continue + try: + response = await backend.request( + "POST", + self._token_url, + headers=_exchange_headers(), + content=self._form(assertion), + timeout=run.attempt_timeout(attempt), + ) + except TransportError as error: + run.transport_failed(error) + continue + result = run.read(response, assertion) + if result is not None: + return result + raise run.exhausted() diff --git a/tests/test_workload_identity.py b/tests/test_workload_identity.py new file mode 100644 index 00000000..6b31504b --- /dev/null +++ b/tests/test_workload_identity.py @@ -0,0 +1,1729 @@ +# @oagen-ignore-file + +"""Workload identity federation: conformance cases WIF-01 to WIF-24. + +Each case is one scenario function that runs twice, from the same code: +against ``WorkOSClient`` as ``test_WIF_NN_`` and against +``AsyncWorkOSClient`` as ``test_WIF_NN_async_``. The scenario talks to a +``Harness`` that hides whether a call is a function call or a coroutine. + +Nothing here touches the network. The token endpoint and the API are mocked at +the httpx2 transport, below the client, so redirects, retries and headers are +the real ones. Time is an injected clock, and backoff is an injected sleeper. +""" + +from __future__ import annotations + +import asyncio +import json +import logging +import re +import threading +import time +import traceback +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any, Callable, Dict, Iterator, List, Optional, Union +from urllib.parse import parse_qs + +import httpx2 +import pytest + +from workos import ( + AsyncWorkOSClient, + AuthenticationError, + Credentials, + CredentialSnapshot, + IdentityTokenProvider, + WorkloadIdentityCredentials, + WorkloadIdentityError, + WorkOSClient, + WorkOSError, + token_env, + token_file, +) +from workos import workload_identity +from workos._credentials import StaticKeyCredentials, apply_snapshot +from workos._errors import ConfigurationError, WorkOSTimeoutError + +CLIENT_ID = "client_wif_test" +ENVIRONMENT_ID = "environment_wif_test" +TOKEN_URL = "https://token.test/oauth2/token" +API_URL = "https://api.test" +ELSEWHERE_URL = "https://elsewhere.test/oauth2/token" + +ENVIRONMENT = ( + "WORKOS_API_KEY", + "WORKOS_CLIENT_ID", + "WORKOS_WIF_TOKEN_URL", + "WORKOS_WIF_SCOPE", + "WORKOS_ENVIRONMENT_ID", + "WORKOS_BASE_URL", +) +OAUTH_CODES = ( + "invalid_grant", + "invalid_target", + "invalid_client", + "unauthorized_client", + "invalid_scope", + "invalid_request", +) +EXCHANGE_ATTEMPTS = workload_identity.MAX_RETRIES + 1 + + +# --- the mock token endpoint and API ---------------------------------------------- + + +@dataclass +class Reply: + """A response a mocked host gives.""" + + status: int = 200 + json: Any = None + headers: Dict[str, str] = field(default_factory=lambda: {}) + text: Optional[str] = None + + def response(self) -> httpx2.Response: + if self.text is not None: + return httpx2.Response( + self.status, content=self.text.encode(), headers=self.headers + ) + return httpx2.Response(self.status, json=self.json, headers=self.headers) + + +def oauth_error(code: str, description: str = "the server said no") -> Reply: + return Reply(400, {"error": code, "error_description": description}) + + +def unauthorized() -> Reply: + return Reply(401, {"message": "Unauthorized"}) + + +@dataclass +class Recorded: + """A request a mocked host received.""" + + method: str + url: str + headers: Dict[str, str] + content: bytes + timeout: Optional[float] = None + + @property + def form(self) -> Dict[str, str]: + fields = parse_qs(self.content.decode(), keep_blank_values=True) + return {name: values[0] for name, values in fields.items()} + + @property + def bearer(self) -> Optional[str]: + value = self.headers.get("authorization") + if value is not None and value.startswith("Bearer "): + return value[len("Bearer ") :] + return value + + +class Endpoint: + """One mocked host: replays scripted replies, then its default one.""" + + def __init__(self) -> None: + self.requests: List[Recorded] = [] + self.script: List[Union[Reply, Exception]] = [] + self.entered = threading.Event() + self._gate: Optional[threading.Event] = None + self._lock = threading.Lock() + + @property + def count(self) -> int: + """Requests this host received. A scripted connection failure is not one.""" + return len(self.requests) + + def bearers(self) -> List[Optional[str]]: + return [request.bearer for request in self.requests] + + def hold(self) -> None: + """Keep every response back until ``release()``.""" + self._gate = threading.Event() + + def release(self) -> None: + if self._gate is not None: + self._gate.set() + + def held(self) -> bool: + gate = self._gate + return gate is not None and not gate.is_set() + + def default(self) -> Reply: + return Reply(200, {"ok": True}) + + def take(self, request: httpx2.Request) -> Union[Reply, Exception]: + with self._lock: + item = self.script.pop(0) if self.script else self.default() + if not isinstance(item, Exception): + self.requests.append( + Recorded( + method=request.method, + url=str(request.url), + headers={k.lower(): v for k, v in request.headers.items()}, + content=request.content, + timeout=request.extensions.get("timeout", {}).get("read"), + ) + ) + self.entered.set() + return item + + +class TokenEndpoint(Endpoint): + """The token endpoint: by default, one new access token per exchange.""" + + def __init__(self) -> None: + super().__init__() + self.expires_in: Any = 300 + self.access_token: Optional[str] = None + self.issued = 0 + + def default(self) -> Reply: + self.issued += 1 + body: Dict[str, Any] = { + "access_token": self.access_token or f"access-{self.issued}", + "token_type": "Bearer", + } + if self.expires_in is not None: + body["expires_in"] = self.expires_in + return Reply(200, body) + + def forms(self) -> List[Dict[str, str]]: + return [request.form for request in self.requests] + + +class Network: + """Routes every httpx2 request, sync or async, to a mocked host.""" + + def __init__(self) -> None: + self.token = TokenEndpoint() + self.api = Endpoint() + self.elsewhere = Endpoint() + self.unexpected: List[str] = [] + self._hosts = { + "token.test": self.token, + "api.test": self.api, + "elsewhere.test": self.elsewhere, + } + + def _endpoint(self, request: httpx2.Request) -> Endpoint: + endpoint = self._hosts.get(request.url.host) + if endpoint is None: + self.unexpected.append(str(request.url)) + raise httpx2.ConnectError("no mock for this host") + return endpoint + + def handle(self, request: httpx2.Request) -> httpx2.Response: + request.read() + endpoint = self._endpoint(request) + item = endpoint.take(request) + deadline = time.monotonic() + 10 + while endpoint.held(): + assert time.monotonic() < deadline, "a held response was never released" + time.sleep(0.001) + if isinstance(item, Exception): + raise item + return item.response() + + async def handle_async(self, request: httpx2.Request) -> httpx2.Response: + await request.aread() + endpoint = self._endpoint(request) + item = endpoint.take(request) + deadline = time.monotonic() + 10 + while endpoint.held(): + assert time.monotonic() < deadline, "a held response was never released" + await asyncio.sleep(0.001) + if isinstance(item, Exception): + raise item + return item.response() + + +@pytest.fixture +def network(monkeypatch: pytest.MonkeyPatch) -> Iterator[Network]: + net = Network() + for name in ENVIRONMENT: + monkeypatch.delenv(name, raising=False) + + def _sync( + _transport: httpx2.HTTPTransport, request: httpx2.Request + ) -> httpx2.Response: + return net.handle(request) + + async def _async( + _transport: httpx2.AsyncHTTPTransport, request: httpx2.Request + ) -> httpx2.Response: + return await net.handle_async(request) + + monkeypatch.setattr(httpx2.HTTPTransport, "handle_request", _sync) + monkeypatch.setattr(httpx2.AsyncHTTPTransport, "handle_async_request", _async) + yield net + for endpoint in (net.token, net.api, net.elsewhere): + endpoint.release() + assert net.unexpected == [], f"requests to unmocked hosts: {net.unexpected}" + + +# --- providers, clock -------------------------------------------------------------- + + +class Provider: + """An identity token provider that counts its calls. + + Returns its values in order and then repeats the last one. A value that is + an exception is raised instead. + """ + + def __init__(self, *values: Union[str, Exception]) -> None: + self._values: List[Union[str, Exception]] = list(values) or ["assertion-1"] + self._lock = threading.Lock() + self.calls = 0 + self.threads: List[int] = [] + + def __call__(self) -> str: + with self._lock: + value = self._values[min(self.calls, len(self._values) - 1)] + self.calls += 1 + self.threads.append(threading.get_ident()) + if isinstance(value, Exception): + raise value + return value + + +class Clock: + def __init__(self) -> None: + self.time = 0.0 + + def now(self) -> float: + return self.time + + +class Counter: + def __init__(self) -> None: + self.value = 0 + self._lock = threading.Lock() + + def increment(self) -> None: + with self._lock: + self.value += 1 + + +# --- the harness: one scenario, both clients ---------------------------------------- + +Operation = Callable[[], Any] + + +class Harness: + """What a scenario needs, for ``WorkOSClient``. ``AsyncHarness`` overrides the rest.""" + + gave_up_error: type = WorkOSTimeoutError + + def __init__( + self, + network: Network, + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, + caplog: pytest.LogCaptureFixture, + ) -> None: + self.network = network + self.token = network.token + self.api = network.api + self.monkeypatch = monkeypatch + self.tmp_path = tmp_path + self.caplog = caplog + self.clock = Clock() + self.sleeps: List[float] = [] + self._clients: List[Any] = [] + + # credentials + + def instrument( + self, credentials: WorkloadIdentityCredentials + ) -> WorkloadIdentityCredentials: + """Give the credentials the fake clock and a sleeper that only records.""" + + async def record(seconds: float) -> None: + self.sleeps.append(seconds) + + credentials._clock = self.clock.now + credentials._sleep = self.sleeps.append + credentials._async_sleep = record + return credentials + + def credentials( + self, provider: Optional[IdentityTokenProvider] = None, **settings: Any + ) -> WorkloadIdentityCredentials: + settings.setdefault("client_id", CLIENT_ID) + settings.setdefault("token_url", TOKEN_URL) + settings.setdefault("environment_id", ENVIRONMENT_ID) + return self.bare_credentials(provider or Provider(), **settings) + + def bare_credentials( + self, provider: IdentityTokenProvider, **settings: Any + ) -> WorkloadIdentityCredentials: + return self.instrument( + WorkloadIdentityCredentials(identity_token_provider=provider, **settings) + ) + + def watch_joins(self, credentials: WorkloadIdentityCredentials) -> Counter: + """Count the callers that joined (or started) a shared exchange.""" + joins = Counter() + for name in ("_join_or_start", "_join_or_start_async"): + original = getattr(credentials, name) + + def joined(original: Callable[[], Any] = original) -> Any: + exchange = original() + joins.increment() + return exchange + + setattr(credentials, name, joined) + return joins + + # clients + + def new_client(self, **kwargs: Any) -> Any: + return WorkOSClient(**kwargs) + + def client(self, credentials: Optional[Credentials] = None, **kwargs: Any) -> Any: + kwargs.setdefault("base_url", API_URL) + if credentials is not None: + kwargs["credentials"] = credentials + client = self.new_client(**kwargs) + self._clients.append(client) + return client + + # operations: built once, run by whichever client this harness drives + + def op_request( + self, + client: Any, + method: str = "GET", + path: Any = ("organizations",), + **kwargs: Any, + ) -> Operation: + return lambda: client.request(method, path, **kwargs) + + def op_resolve( + self, credentials: Credentials, timeout: Optional[float] = None + ) -> Operation: + return lambda: credentials.resolve(timeout=timeout) + + def run(self, operation: Operation) -> Any: + return operation() + + def start(self, operation: Operation) -> Any: + """Start an operation without waiting for it. See ``outcome``.""" + caller = _ThreadCaller(operation) + caller.thread.start() + return caller + + def outcome(self, caller: Any) -> Any: + """The started operation's result, or the exception it raised.""" + caller.thread.join(10) + assert not caller.thread.is_alive(), "a caller never finished" + return caller.outcome + + def wait_until(self, condition: Callable[[], bool]) -> None: + deadline = time.monotonic() + 10 + while not condition(): + assert time.monotonic() < deadline, "timed out waiting for a condition" + time.sleep(0.001) + + def start_impatient(self, client: Any) -> Any: + """Start a request whose caller will give up while the exchange is held. + + A synchronous caller gives up through its request timeout. + """ + return self.start(self.op_request(client, request_options={"timeout": 0.25})) + + def give_up(self, caller: Any) -> Any: + return self.outcome(caller) + + # conveniences + + def get(self, client: Any, **kwargs: Any) -> Any: + return self.run(self.op_request(client, **kwargs)) + + def resolve( + self, credentials: Credentials, timeout: Optional[float] = None + ) -> CredentialSnapshot: + return self.run(self.op_resolve(credentials, timeout)) + + def failure(self, operation: Operation) -> BaseException: + """Run an operation that must fail, and return what it raised.""" + with pytest.raises(Exception) as caught: + self.run(operation) + return caught.value + + def close(self) -> None: + for client in self._clients: + client.close() + + +class _ThreadCaller: + def __init__(self, operation: Operation) -> None: + self.outcome: Any = None + self._operation = operation + self.thread = threading.Thread(target=self._work, daemon=True) + + def _work(self) -> None: + try: + self.outcome = self._operation() + except BaseException as error: + self.outcome = error + + +class AsyncHarness(Harness): + """The same scenarios against ``AsyncWorkOSClient``, on a loop the harness owns.""" + + gave_up_error = asyncio.CancelledError + + def __init__(self, *args: Any) -> None: + super().__init__(*args) + self.loop = asyncio.new_event_loop() + + def new_client(self, **kwargs: Any) -> Any: + return AsyncWorkOSClient(**kwargs) + + def op_resolve( + self, credentials: Credentials, timeout: Optional[float] = None + ) -> Operation: + return lambda: credentials.aresolve(timeout=timeout) + + def run(self, operation: Operation) -> Any: + return self.loop.run_until_complete(operation()) + + def start(self, operation: Operation) -> Any: + return self.loop.create_task(operation()) + + def outcome(self, caller: Any) -> Any: + async def settle() -> Any: + return (await asyncio.gather(caller, return_exceptions=True))[0] + + return self.loop.run_until_complete(asyncio.wait_for(settle(), 10)) + + def wait_until(self, condition: Callable[[], bool]) -> None: + async def poll() -> None: + while not condition(): + await asyncio.sleep(0.001) + + self.loop.run_until_complete(asyncio.wait_for(poll(), 10)) + + def start_impatient(self, client: Any) -> Any: + """An asynchronous caller gives up by having its task canceled.""" + return self.start(self.op_request(client)) + + def give_up(self, caller: Any) -> Any: + caller.cancel() + return self.outcome(caller) + + def close(self) -> None: + async def shut_down() -> None: + for client in self._clients: + await client.close() + pending = [ + task + for task in asyncio.all_tasks() + if task is not asyncio.current_task() + ] + for task in pending: + task.cancel() + await asyncio.gather(*pending, return_exceptions=True) + + try: + self.loop.run_until_complete(shut_down()) + self.loop.run_until_complete(self.loop.shutdown_default_executor()) + finally: + self.loop.close() + + +@pytest.fixture +def sync_harness( + network: Network, + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, + caplog: pytest.LogCaptureFixture, +) -> Iterator[Harness]: + harness = Harness(network, monkeypatch, tmp_path, caplog) + yield harness + harness.close() + + +@pytest.fixture +def async_harness( + network: Network, + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, + caplog: pytest.LogCaptureFixture, +) -> Iterator[Harness]: + harness = AsyncHarness(network, monkeypatch, tmp_path, caplog) + yield harness + harness.close() + + +_CASE_NAME = re.compile(r"^(WIF_\d+)_(.+)$") + + +def scenario(function: Callable[[Harness], None]) -> Callable[[Harness], None]: + """Register a scenario as two tests, one per client. + + ``WIF_01_foo`` becomes ``test_WIF_01_foo`` and ``test_WIF_01_async_foo``, so + the case ID is in both names. A scenario with no case ID becomes + ``test_foo`` and ``test_async_foo``. + """ + case = _CASE_NAME.match(function.__name__) + if case is not None: + sync_name = f"test_{case.group(1)}_{case.group(2)}" + async_name = f"test_{case.group(1)}_async_{case.group(2)}" + else: + sync_name = f"test_{function.__name__}" + async_name = f"test_async_{function.__name__}" + + def run_sync(sync_harness: Harness) -> None: + function(sync_harness) + + def run_async(async_harness: Harness) -> None: + function(async_harness) + + for name, test in ((sync_name, run_sync), (async_name, run_async)): + test.__name__ = test.__qualname__ = name + test.__doc__ = function.__doc__ + assert name not in function.__globals__, f"duplicate test name: {name}" + function.__globals__[name] = test + return function + + +def secrets_in(error: BaseException, *secrets: str) -> List[str]: + """Every place a secret shows up in an error, its causes, or their tracebacks.""" + found: List[str] = [] + seen: List[BaseException] = [] + current: Optional[BaseException] = error + while current is not None and current not in seen: + seen.append(current) + rendered = { + "str": str(current), + "repr": repr(current), + "message": str(getattr(current, "message", "")), + "traceback": "".join( + traceback.format_exception( + type(current), current, current.__traceback__ + ) + ), + } + for where, text in rendered.items(): + found.extend( + f"{type(current).__name__}.{where}: {secret}" + for secret in secrets + if secret in text + ) + current = current.__cause__ or current.__context__ + return found + + +# --- conformance cases --------------------------------------------------------------- + + +@scenario +def WIF_01_first_request_triggers_one_exchange_post(h: Harness) -> None: + provider = Provider("assertion-1") + h.get(h.client(h.credentials(provider))) + + assert h.token.count == 1 + post = h.token.requests[0] + assert post.method == "POST" + assert post.url == TOKEN_URL + assert post.headers["content-type"] == "application/x-www-form-urlencoded" + assert post.headers["accept"] == "application/json" + assert "authorization" not in post.headers + assert post.form == { + "grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer", + "assertion": "assertion-1", + "client_id": "client_wif_test", + "resource": "https://api.workos.com", + } + assert "scope" not in post.form + assert "client_secret" not in post.form + + # Again on a new instance, with a scope. + h.get(h.client(h.credentials(Provider("assertion-1"), scope="organizations:write"))) + + assert h.token.count == 2 + scoped = h.token.requests[1] + assert scoped.form["scope"] == "organizations:write" + assert "client_secret" not in scoped.form + assert "authorization" not in scoped.headers + + +@scenario +def WIF_02_api_request_carries_the_access_token_and_environment_header( + h: Harness, +) -> None: + # No API key and no client ID: the credentials alone are enough to build a client. + h.get(h.client(h.credentials())) + + assert h.api.count == 1 + request = h.api.requests[0] + assert request.headers["authorization"] == "Bearer access-1" + assert request.headers["x-url-environment-id"] == "environment_wif_test" + + +@scenario +def WIF_03_second_request_reuses_the_cached_token(h: Harness) -> None: + client = h.client(h.credentials()) + + h.get(client) + h.get(client) + + assert h.token.count == 1 + assert h.api.bearers() == ["access-1", "access-1"] + + +@scenario +def WIF_04_token_is_refreshed_when_less_than_60_seconds_remain(h: Harness) -> None: + h.token.expires_in = 300 + client = h.client(h.credentials()) + + h.get(client) + h.clock.time = 239 + h.get(client) + assert h.token.count == 1 + + h.clock.time = 241 + h.get(client) + assert h.token.count == 2 + assert h.api.bearers() == ["access-1", "access-1", "access-2"] + + +@scenario +def WIF_05_refresh_threshold_is_20_percent_of_a_short_lifetime(h: Harness) -> None: + h.token.expires_in = 100 + client = h.client(h.credentials()) + + h.get(client) + h.clock.time = 79 + h.get(client) + assert h.token.count == 1 + + h.clock.time = 81 + h.get(client) + assert h.token.count == 2 + + +@scenario +def WIF_06_missing_expires_in_is_treated_as_300_seconds(h: Harness) -> None: + h.token.expires_in = None + client = h.client(h.credentials()) + + h.get(client) + h.clock.time = 239 + h.get(client) + assert h.token.count == 1 + + h.clock.time = 241 + h.get(client) + assert h.token.count == 2 + + +@scenario +def WIF_07_two_instances_never_share_a_cached_token(h: Harness) -> None: + first = h.client(h.credentials()) + second = h.client(h.credentials()) + + h.get(first) + h.get(second) + + assert h.token.count == 2 + assert h.api.bearers() == ["access-1", "access-2"] + + +@scenario +def WIF_08_concurrent_first_requests_produce_exactly_one_exchange(h: Harness) -> None: + provider = Provider() + credentials = h.credentials(provider) + joins = h.watch_joins(credentials) + client = h.client(credentials) + h.token.hold() + + callers = [h.start(h.op_request(client)) for _ in range(20)] + # The token endpoint answers only once all 20 callers wait on the exchange. + h.wait_until(lambda: joins.value == 20 and h.token.entered.is_set()) + h.token.release() + outcomes = [h.outcome(caller) for caller in callers] + + assert [o for o in outcomes if isinstance(o, BaseException)] == [] + assert h.token.count == 1 + assert provider.calls == 1 + assert h.api.bearers() == ["access-1"] * 20 + + +@scenario +def WIF_09_a_401_invalidates_the_token_exchanges_again_and_retries_once( + h: Harness, +) -> None: + client = h.client(h.credentials()) + h.api.script.append(unauthorized()) + + assert h.get(client) == {"ok": True} + + assert h.token.count == 2 + assert h.api.bearers() == ["access-1", "access-2"] + + +@scenario +def WIF_10_a_second_401_after_recovery_is_returned_to_the_caller(h: Harness) -> None: + client = h.client(h.credentials()) + h.api.script.extend(unauthorized() for _ in range(10)) + + error = h.failure(h.op_request(client)) + + assert isinstance(error, AuthenticationError) + assert h.token.count == 2 + assert h.api.count == 2 + assert h.api.bearers() == ["access-1", "access-2"] + + +@scenario +def WIF_11_a_late_401_for_an_old_generation_keeps_the_newer_token(h: Harness) -> None: + credentials = h.credentials() + client = h.client(credentials) + + first = h.resolve(credentials) + assert first.headers["Authorization"] == "Bearer access-1" + credentials.invalidate(first.generation) + second = h.resolve(credentials) + assert second.headers["Authorization"] == "Bearer access-2" + assert second.generation > first.generation + + # A 401 for the first token arrives late. + credentials.invalidate(first.generation) + h.get(client) + + assert h.resolve(credentials).generation == second.generation + assert h.token.count == 2 + assert h.api.bearers() == ["access-2"] + + +@scenario +def WIF_12_transport_retries_do_not_reset_the_401_recovery_allowance( + h: Harness, +) -> None: + client = h.client(h.credentials()) + h.api.script.extend( + [ + unauthorized(), + Reply(503, {"message": "Unavailable"}, {"Retry-After": "0"}), + unauthorized(), + Reply(200, {"ok": True}), + ] + ) + + error = h.failure(h.op_request(client)) + + assert isinstance(error, AuthenticationError) + assert h.token.count == 2 + # Exactly three attempts: the 200 that would have come fourth is never asked for. + assert h.api.count == 3 + assert len(h.api.script) == 1 + + +@scenario +def WIF_13_the_401_retry_sends_the_same_body_and_idempotency_key(h: Harness) -> None: + client = h.client(h.credentials()) + h.api.script.append(unauthorized()) + + h.run(h.op_request(client, method="POST", body={"name": "Acme", "n": 1})) + + assert h.api.count == 2 + first, second = h.api.requests + assert json.loads(first.content) == {"name": "Acme", "n": 1} + assert first.content == second.content + assert first.headers["idempotency-key"] + assert first.headers["idempotency-key"] == second.headers["idempotency-key"] + assert [first.bearer, second.bearer] == ["access-1", "access-2"] + + +@scenario +def WIF_14_exchange_is_retried_on_503_and_429_honoring_retry_after( + h: Harness, +) -> None: + provider = Provider() + h.token.script.extend( + [ + Reply(503, {"message": "Unavailable"}), + Reply(429, {"message": "Slow down"}, {"Retry-After": "0"}), + ] + ) + + h.get(h.client(h.credentials(provider))) + + assert h.token.count == 3 + assert provider.calls == 3 + assert h.api.bearers() == ["access-1"] + # The 429's Retry-After: 0 is what the second backoff waited. + assert h.sleeps[1] == 0 + + +@scenario +def WIF_14_exchange_is_retried_on_a_connection_failure(h: Harness) -> None: + provider = Provider() + h.token.script.append(httpx2.ConnectError("connection refused")) + + h.get(h.client(h.credentials(provider))) + + assert provider.calls == 2 + assert h.token.count == 1 + assert h.api.bearers() == ["access-1"] + + +@scenario +def WIF_14_exchange_is_retried_on_a_timeout(h: Harness) -> None: + provider = Provider() + h.token.script.append(httpx2.ReadTimeout("the token endpoint did not answer")) + + h.get(h.client(h.credentials(provider))) + + assert provider.calls == 2 + assert h.api.bearers() == ["access-1"] + # An attempt gets a share of the 30-second deadline, not all of it, so + # that a timeout leaves time to try again. + retry = h.token.requests[0] + assert retry.timeout is not None + assert 0 < retry.timeout <= workload_identity.EXCHANGE_DEADLINE_SECONDS / 3 + + +@scenario +def WIF_14_provider_is_invoked_again_after_it_raises(h: Harness) -> None: + provider = Provider( + RuntimeError("the metadata server is warming up"), "assertion-2" + ) + + h.get(h.client(h.credentials(provider))) + + assert provider.calls == 2 + assert h.token.count == 1 + assert h.token.forms()[0]["assertion"] == "assertion-2" + assert h.api.bearers() == ["access-1"] + + +@scenario +def WIF_14_retry_after_is_what_the_sleeper_is_asked_to_wait(h: Harness) -> None: + h.token.script.append(Reply(429, {"message": "Slow down"}, {"Retry-After": "1"})) + + h.get(h.client(h.credentials())) + + assert h.token.count == 2 + assert len(h.sleeps) == 1 + assert h.sleeps[0] >= 1 + + +@scenario +def WIF_15_an_oauth_error_is_not_retried_and_carries_its_code(h: Harness) -> None: + for code in OAUTH_CODES: + before = h.token.count + provider = Provider() + h.token.script.append(oauth_error(code, f"{code} from the server")) + + error = h.failure(h.op_request(h.client(h.credentials(provider)))) + + assert isinstance(error, WorkloadIdentityError), code + assert isinstance(error, WorkOSError) + assert error.code == code + assert error.description == f"{code} from the server" + assert error.hint + assert str(error) == f"{code}: {error.hint} {code} from the server" + assert h.token.count - before == 1 + assert provider.calls == 1 + assert h.api.count == 0 + assert h.sleeps == [] + + +@scenario +def WIF_16_after_a_failed_exchange_the_next_request_exchanges_afresh( + h: Harness, +) -> None: + client = h.client(h.credentials()) + h.token.script.append(oauth_error("invalid_grant")) + + error = h.failure(h.op_request(client)) + assert isinstance(error, WorkloadIdentityError) + + h.get(client) + + assert h.token.count == 2 + assert h.api.bearers() == ["access-1"] + + +@scenario +def WIF_17_tokens_never_appear_in_errors_or_logs(h: Harness) -> None: + assertion = "SECRET-ASSERTION-VALUE" + access_token = "SECRET-ACCESS-VALUE" + h.caplog.set_level(logging.DEBUG) + h.token.access_token = access_token + errors: List[BaseException] = [] + + def fail_with(provider: IdentityTokenProvider) -> None: + client = h.client(h.credentials(provider)) + errors.append(h.failure(h.op_request(client))) + + # An invalid_grant exchange. + h.token.script.append(oauth_error("invalid_grant")) + fail_with(Provider(assertion)) + # A 500 from the token endpoint until the retries run out. + h.token.script.extend( + Reply(500, {"message": "boom"}) for _ in range(EXCHANGE_ATTEMPTS) + ) + fail_with(Provider(assertion)) + # A provider that raises. + fail_with(Provider(RuntimeError("the provider broke"))) + # A second 401 from the API, after the access token was issued and sent. + h.api.script.extend(unauthorized() for _ in range(2)) + fail_with(Provider(assertion)) + + assert [type(error).__name__ for error in errors] == [ + "WorkloadIdentityError", + "WorkloadIdentityError", + "WorkloadIdentityError", + "AuthenticationError", + ] + assert h.api.bearers() == [access_token, access_token] + for error in errors: + assert secrets_in(error, assertion, access_token) == [] + for record in h.caplog.records: + logged = f"{record.getMessage()} {record.__dict__!r}" + assert assertion not in logged + assert access_token not in logged + assert assertion not in h.caplog.text + assert access_token not in h.caplog.text + + +@scenario +def WIF_18_the_exchange_does_not_follow_redirects(h: Harness) -> None: + h.token.script.append(Reply(307, None, {"Location": ELSEWHERE_URL})) + + error = h.failure(h.op_request(h.client(h.credentials()))) + + assert isinstance(error, WorkloadIdentityError) + assert error.code == "exchange_failed" + assert h.network.elsewhere.count == 0 + assert h.token.count == 1 + assert h.api.count == 0 + + +@scenario +def WIF_19_api_key_together_with_credentials_is_a_configuration_error( + h: Harness, +) -> None: + credentials = h.credentials() + + with pytest.raises(ValueError, match="api_key or credentials, not both"): + h.client(credentials, api_key="sk_test_explicit") + + assert h.token.count == 0 + assert h.api.count == 0 + + +@scenario +def WIF_20_explicit_credentials_win_over_the_environment_api_key(h: Harness) -> None: + h.monkeypatch.setenv("WORKOS_API_KEY", "sk_test_env") + + # (a) Valid credentials are used; the environment key is ignored. + client = h.client(h.credentials()) + h.get(client) + assert h.api.bearers() == ["access-1"] + assert client._api_key is None + + # (b) Credentials with no token URL, explicit or in the environment, cannot be built. + with pytest.raises(WorkloadIdentityError) as missing: + h.bare_credentials( + Provider(), client_id=CLIENT_ID, environment_id=ENVIRONMENT_ID + ) + assert missing.value.code == "invalid_configuration" + assert "token_url is required (or set WORKOS_WIF_TOKEN_URL)" in str(missing.value) + + # (c) A failing exchange is an error, never a fall back to the key. + h.token.script.append(oauth_error("invalid_client")) + error = h.failure(h.op_request(h.client(h.credentials()))) + assert isinstance(error, WorkloadIdentityError) + assert error.code == "invalid_client" + + sent = [*h.api.requests, *h.token.requests] + assert all("sk_test_env" not in str(request.headers) for request in sent) + assert all(b"sk_test_env" not in request.content for request in sent) + assert h.api.count == 1 + + +@scenario +def WIF_21_token_file_is_read_again_on_every_exchange(h: Harness) -> None: + path = h.tmp_path / "identity-token" + path.write_text("assertion-1\n") + client = h.client(h.credentials(token_file(path))) + + h.get(client) + path.write_text(" assertion-2\n\n") + h.clock.time = 241 + h.get(client) + + assert [form["assertion"] for form in h.token.forms()] == [ + "assertion-1", + "assertion-2", + ] + + +@scenario +def WIF_22_env_and_callback_providers_and_environment_defaults(h: Harness) -> None: + # (a) token_env reads the variable. + h.monkeypatch.setenv("MY_JWT", "assertion-env") + h.get(h.client(h.credentials(token_env("MY_JWT")))) + assert h.token.forms()[-1]["assertion"] == "assertion-env" + + # (b) A callback is any callable; no wrapper is needed. + h.get(h.client(h.credentials(lambda: "assertion-cb"))) + assert h.token.forms()[-1]["assertion"] == "assertion-cb" + + # (c) Omitted settings default from the environment. + h.monkeypatch.setenv("WORKOS_CLIENT_ID", "client_env") + h.monkeypatch.setenv("WORKOS_WIF_TOKEN_URL", TOKEN_URL) + h.monkeypatch.setenv("WORKOS_WIF_SCOPE", "scope_env") + h.monkeypatch.setenv("WORKOS_ENVIRONMENT_ID", "environment_env") + before = h.token.count + h.get(h.client(h.bare_credentials(Provider()))) + assert h.token.count == before + 1 + assert h.token.requests[-1].url == TOKEN_URL + assert h.token.forms()[-1]["client_id"] == "client_env" + assert h.token.forms()[-1]["scope"] == "scope_env" + assert h.api.requests[-1].headers["x-url-environment-id"] == "environment_env" + + # (d) Explicit values win over the environment. + h.get( + h.client( + h.bare_credentials( + Provider(), + client_id="client_explicit", + scope="scope_explicit", + environment_id="environment_explicit", + ) + ) + ) + assert h.token.forms()[-1]["client_id"] == "client_explicit" + assert h.token.forms()[-1]["scope"] == "scope_explicit" + assert h.api.requests[-1].headers["x-url-environment-id"] == "environment_explicit" + + +@scenario +def WIF_23_canceling_one_waiter_does_not_cancel_the_shared_exchange( + h: Harness, +) -> None: + provider = Provider() + credentials = h.credentials(provider) + joins = h.watch_joins(credentials) + client = h.client(credentials) + h.token.hold() + + caller_a = h.start_impatient(client) + caller_b = h.start(h.op_request(client)) + h.wait_until(lambda: joins.value == 2 and h.token.entered.is_set()) + + # A gives up while the token endpoint still holds its response. + gave_up = h.give_up(caller_a) + assert isinstance(gave_up, h.gave_up_error) + assert h.token.held() + + h.token.release() + assert h.outcome(caller_b) == {"ok": True} + assert h.token.count == 1 + assert provider.calls == 1 + assert h.api.bearers() == ["access-1"] + + +@scenario +def WIF_24_static_api_key_clients_are_unchanged(h: Harness) -> None: + client = h.client(api_key="sk_test_static") + + h.get(client) + request = h.api.requests[0] + assert request.headers["authorization"] == "Bearer sk_test_static" + assert "x-url-environment-id" not in request.headers + + h.api.script.extend([unauthorized(), Reply(200, {"ok": True})]) + error = h.failure(h.op_request(client)) + + assert isinstance(error, AuthenticationError) + # One attempt for the 401: the 200 scripted after it is never asked for. + assert h.api.count == 2 + assert len(h.api.script) == 1 + assert h.token.count == 0 + + +# --- beyond the numbered cases -------------------------------------------------------- + + +@scenario +def invalid_token_responses_are_terminal(h: Harness) -> None: + replies = [ + (Reply(200, text="not json"), "invalid_response"), + (Reply(200, ["access-1"]), "invalid_response"), + (Reply(200, {"token_type": "Bearer"}), "invalid_response"), + (Reply(200, {"access_token": ""}), "invalid_response"), + (Reply(200, {"access_token": 7}), "invalid_response"), + (Reply(404, text="not found"), "invalid_response"), + (Reply(403, {"error": "access_denied"}), "access_denied"), + (Reply(302, {"error": "temporarily_unavailable"}), "temporarily_unavailable"), + ] + for reply, code in replies: + before = h.token.count + h.token.script.append(reply) + + error = h.failure(h.op_request(h.client(h.credentials()))) + + assert isinstance(error, WorkloadIdentityError) + assert error.code == code + assert error.hint + assert h.token.count - before == 1 + assert h.sleeps == [] + assert h.api.count == 0 + + +@scenario +def exhausted_exchange_retries_report_the_last_failure(h: Harness) -> None: + # A 5xx is retried even when its body carries an OAuth error, and that code + # is reported once the retries run out. + h.token.script.extend( + Reply(503, {"error": "temporarily_unavailable", "error_description": "busy"}) + for _ in range(EXCHANGE_ATTEMPTS) + ) + error = h.failure(h.op_request(h.client(h.credentials()))) + assert isinstance(error, WorkloadIdentityError) + assert (error.code, error.description) == ("temporarily_unavailable", "busy") + assert h.token.count == EXCHANGE_ATTEMPTS + assert len(h.sleeps) == EXCHANGE_ATTEMPTS - 1 + + # Any 5xx counts, not only the statuses the API retry loop lists. + h.token.script.extend(Reply(501, text="nope") for _ in range(EXCHANGE_ATTEMPTS)) + error = h.failure(h.op_request(h.client(h.credentials()))) + assert isinstance(error, WorkloadIdentityError) + assert error.code == "exchange_failed" + assert h.token.count == 2 * EXCHANGE_ATTEMPTS + + # Connection failures. + h.token.script.extend( + httpx2.ConnectError("connection refused") for _ in range(EXCHANGE_ATTEMPTS) + ) + error = h.failure(h.op_request(h.client(h.credentials()))) + assert isinstance(error, WorkloadIdentityError) + assert error.code == "exchange_failed" + + # A provider that always raises: its error is the cause, and its message is kept. + broken = Provider(RuntimeError("Add `permissions: id-token: write`")) + error = h.failure(h.op_request(h.client(h.credentials(broken)))) + assert isinstance(error, WorkloadIdentityError) + assert error.code == "provider_failed" + assert "permissions: id-token: write" in str(error) + assert isinstance(error.__cause__, RuntimeError) + assert broken.calls == EXCHANGE_ATTEMPTS + assert h.api.count == 0 + + +@scenario +def empty_or_non_string_assertions_are_provider_failures(h: Harness) -> None: + for provider in (Provider(""), lambda: None, lambda: 12345): + credentials = h.credentials(provider) # type: ignore[arg-type] + error = h.failure(h.op_resolve(credentials)) + assert isinstance(error, WorkloadIdentityError) + assert error.code == "provider_failed" + assert h.token.count == 0 + + +@scenario +def unusable_expires_in_values_fall_back_to_300_seconds(h: Harness) -> None: + for expires_in in ("300", 0, -5, True, None): + h.token.expires_in = expires_in + h.clock.time = 0 + credentials = h.credentials() + client = h.client(credentials) + before = h.token.count + + h.get(client) + h.clock.time = 239 + h.get(client) + assert h.token.count == before + 1, expires_in + h.clock.time = 241 + h.get(client) + assert h.token.count == before + 2, expires_in + + +@scenario +def an_assertion_echoed_by_the_server_is_redacted(h: Harness) -> None: + assertion = "SECRET-ASSERTION-VALUE" + h.token.script.append( + oauth_error(f"bad_{assertion}", f"assertion {assertion} was rejected") + ) + + error = h.failure(h.op_resolve(h.credentials(Provider(assertion)))) + + assert isinstance(error, WorkloadIdentityError) + assert error.code == "bad_[redacted]" + assert error.description == "assertion [redacted] was rejected" + assert secrets_in(error, assertion) == [] + + +@scenario +def a_long_error_description_is_cut_to_500_characters(h: Harness) -> None: + h.token.script.append(oauth_error("invalid_grant", "x" * 2000)) + + error = h.failure(h.op_resolve(h.credentials())) + + assert isinstance(error, WorkloadIdentityError) + assert error.description == "x" * 500 + + +@scenario +def a_per_request_authorization_header_wins_over_a_static_key_only( + h: Harness, +) -> None: + # With an API key the per-request header wins, as it always has. + static = h.client(api_key="sk_test_static") + h.get( + static, + request_options={"extra_headers": {"Authorization": "Bearer per-request"}}, + ) + assert h.api.requests[-1].bearer == "per-request" + + # With credentials, the snapshot overwrites it, whatever its case, and the + # request is recovered from a 401 like any other. + client = h.client(h.credentials()) + for name in ("Authorization", "authorization"): + h.get(client, request_options={"extra_headers": {name: "Bearer per-request"}}) + assert h.api.requests[-1].headers["authorization"] == "Bearer access-1" + assert h.api.requests[-1].headers["x-url-environment-id"] == ENVIRONMENT_ID + h.api.script.append(unauthorized()) + h.get( + client, + request_options={"extra_headers": {"Authorization": "Bearer per-request"}}, + ) + assert h.api.bearers()[-2:] == ["access-1", "access-2"] + assert h.token.count == 2 + + +@scenario +def an_exchange_that_outruns_its_deadline_is_given_up(h: Harness) -> None: + h.monkeypatch.setattr(workload_identity, "EXCHANGE_DEADLINE_SECONDS", 0.05) + h.monkeypatch.setattr(workload_identity, "_DEADLINE_GRACE_SECONDS", 0.01) + stuck = threading.Event() + calls = Counter() + + def provider() -> str: + calls.increment() + if calls.value == 1: + # Never returns in time. A thread cannot be interrupted. + stuck.wait(10) + return "assertion-1" + + credentials = h.credentials(provider) + try: + error = h.failure(h.op_resolve(credentials)) + assert isinstance(error, WorkloadIdentityError) + assert error.code == "exchange_failed" + assert "did not finish" in error.description + + # The stuck exchange does not block the next one. + assert h.resolve(credentials).headers["Authorization"] == "Bearer access-1" + assert calls.value == 2 + finally: + stuck.set() + + +@scenario +def credentials_can_be_resolved_without_a_client(h: Harness) -> None: + credentials = h.credentials() + + snapshot = h.resolve(credentials) + + assert dict(snapshot.headers) == { + "Authorization": "Bearer access-1", + "x-url-environment-id": ENVIRONMENT_ID, + } + assert snapshot.recoverable is True + assert snapshot.generation == 1 + assert "access-1" not in repr(snapshot) + assert h.resolve(credentials) == snapshot + + +@scenario +def a_workload_identity_client_cannot_start_the_feature_flags_runtime( + h: Harness, +) -> None: + # The runtime client polls outside the request path, with the API key. It + # refuses a client that has none instead of polling unauthenticated. + client = h.client(h.credentials()) + + with pytest.raises(ConfigurationError): + client.create_feature_flags_runtime_client() + + +# --- one client only ----------------------------------------------------------------- + + +def test_sync_client_rejects_an_asynchronous_provider(sync_harness: Harness) -> None: + h = sync_harness + calls = Counter() + + async def provider() -> str: + calls.increment() + return "assertion-1" + + error = h.failure(h.op_resolve(h.credentials(provider))) + + assert isinstance(error, WorkloadIdentityError) + assert error.code == "provider_failed" + assert "AsyncWorkOSClient" in error.description + # Not retried: calling it again cannot help. + assert calls.value == 0 and h.sleeps == [] + assert h.token.count == 0 + + +def test_sync_waiter_times_out_without_failing_the_exchange( + sync_harness: Harness, +) -> None: + h = sync_harness + credentials = h.credentials() + h.token.hold() + + with pytest.raises(WorkOSTimeoutError): + credentials.resolve(timeout=0.05) + + h.token.release() + assert credentials.resolve().headers["Authorization"] == "Bearer access-1" + assert h.token.count == 1 + + +def test_async_client_awaits_a_coroutine_provider(async_harness: Harness) -> None: + h = async_harness + threads: List[int] = [] + + async def provider() -> str: + threads.append(threading.get_ident()) + await asyncio.sleep(0) + return "assertion-async" + + h.get(h.client(h.credentials(provider))) + + assert h.token.forms()[0]["assertion"] == "assertion-async" + # Awaited on the event loop, not sent to a worker thread. + assert threads == [threading.get_ident()] + + +def test_async_client_awaits_a_callable_object_with_an_async_call( + async_harness: Harness, +) -> None: + h = async_harness + + class AsyncProvider: + async def __call__(self) -> str: + return "assertion-object" + + h.get(h.client(h.credentials(AsyncProvider()))) + + assert h.token.forms()[0]["assertion"] == "assertion-object" + + +def test_async_client_runs_a_blocking_provider_off_the_event_loop( + async_harness: Harness, +) -> None: + h = async_harness + provider = Provider() + + h.get(h.client(h.credentials(provider))) + + assert provider.calls == 1 + assert provider.threads != [threading.get_ident()] + + +def test_async_client_awaits_an_awaitable_from_a_plain_callable( + async_harness: Harness, +) -> None: + h = async_harness + + async def fetch() -> str: + return "assertion-lambda" + + h.get(h.client(h.credentials(lambda: fetch()))) + + assert h.token.forms()[0]["assertion"] == "assertion-lambda" + + +def test_async_waiter_times_out_without_failing_the_exchange( + async_harness: Harness, +) -> None: + h = async_harness + credentials = h.credentials() + h.token.hold() + + error = h.failure(h.op_resolve(credentials, timeout=0.05)) + assert isinstance(error, WorkOSTimeoutError) + + h.token.release() + assert h.resolve(credentials).headers["Authorization"] == "Bearer access-1" + assert h.token.count == 1 + + +def test_async_exchange_canceled_before_it_ran_does_not_block_the_next( + async_harness: AsyncHarness, +) -> None: + h = async_harness + credentials = h.credentials() + + async def never_runs() -> Any: + raise AssertionError("canceled before its first step") + + stale = h.loop.create_task(never_runs()) + stale.cancel() + h.outcome(stale) + credentials._async_inflight = stale + + assert h.resolve(credentials).headers["Authorization"] == "Bearer access-1" + + +def test_one_credentials_instance_serves_both_kinds_of_client( + sync_harness: Harness, async_harness: Harness +) -> None: + credentials = sync_harness.credentials() + async_harness.instrument(credentials) + sync_client = sync_harness.client(credentials) + async_client = async_harness.client(credentials) + + sync_harness.get(sync_client) + async_harness.get(async_client) + assert sync_harness.token.count == 1 + + # Past the refresh threshold, whichever client asks first exchanges. + async_harness.clock.time = 241 + async_harness.get(async_client) + sync_harness.get(sync_client) + + assert sync_harness.token.count == 2 + assert sync_harness.api.bearers() == [ + "access-1", + "access-1", + "access-2", + "access-2", + ] + + +# --- configuration ------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("missing", "variable"), + [ + ("client_id", "WORKOS_CLIENT_ID"), + ("token_url", "WORKOS_WIF_TOKEN_URL"), + ("environment_id", "WORKOS_ENVIRONMENT_ID"), + ], +) +def test_a_missing_required_setting_fails_at_construction( + network: Network, missing: str, variable: str +) -> None: + settings = { + "client_id": CLIENT_ID, + "token_url": TOKEN_URL, + "environment_id": ENVIRONMENT_ID, + } + del settings[missing] + + with pytest.raises(WorkloadIdentityError) as caught: + WorkloadIdentityCredentials(identity_token_provider=Provider(), **settings) + + assert caught.value.code == "invalid_configuration" + assert caught.value.description == f"{missing} is required (or set {variable})" + assert caught.value.hint == ( + "Workload identity credentials are missing a required setting." + ) + assert network.token.count == 0 + + +def test_a_provider_that_is_not_callable_fails_at_construction( + network: Network, +) -> None: + with pytest.raises(WorkloadIdentityError) as caught: + WorkloadIdentityCredentials( + identity_token_provider="assertion-1", # type: ignore[arg-type] + client_id=CLIENT_ID, + token_url=TOKEN_URL, + environment_id=ENVIRONMENT_ID, + ) + + assert caught.value.code == "invalid_configuration" + + +def test_settings_are_read_only(network: Network) -> None: + credentials = WorkloadIdentityCredentials( + identity_token_provider=Provider(), + client_id=CLIENT_ID, + token_url=TOKEN_URL, + environment_id=ENVIRONMENT_ID, + ) + + assert credentials.client_id == CLIENT_ID + assert credentials.token_url == TOKEN_URL + assert credentials.environment_id == ENVIRONMENT_ID + assert credentials.resource == "https://api.workos.com" + assert credentials.scope is None + with pytest.raises(AttributeError): + credentials.token_url = "https://elsewhere.test" # type: ignore[misc] + assert "access" not in repr(credentials) + + +def test_the_environment_alone_never_turns_workload_identity_on( + network: Network, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setenv("WORKOS_CLIENT_ID", "client_env") + monkeypatch.setenv("WORKOS_WIF_TOKEN_URL", TOKEN_URL) + monkeypatch.setenv("WORKOS_ENVIRONMENT_ID", "environment_env") + monkeypatch.setenv("WORKOS_API_KEY", "sk_test_env") + + with WorkOSClient(base_url=API_URL) as client: + client.request("GET", ("organizations",)) + + assert network.token.count == 0 + assert network.api.bearers() == ["sk_test_env"] + assert "x-url-environment-id" not in network.api.requests[0].headers + + +def test_an_empty_api_key_is_not_a_conflict(network: Network) -> None: + credentials = WorkloadIdentityCredentials( + identity_token_provider=Provider(), + client_id=CLIENT_ID, + token_url=TOKEN_URL, + environment_id=ENVIRONMENT_ID, + ) + + with WorkOSClient(api_key="", credentials=credentials) as client: + assert client._api_key is None + + +def test_a_public_client_cannot_take_credentials(network: Network) -> None: + credentials = WorkloadIdentityCredentials( + identity_token_provider=Provider(), + client_id=CLIENT_ID, + token_url=TOKEN_URL, + environment_id=ENVIRONMENT_ID, + ) + + with pytest.raises(ValueError, match="public client"): + WorkOSClient(client_id="client_123", is_public=True, credentials=credentials) + + +def test_token_file_and_token_env_fail_without_a_token( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + with pytest.raises(FileNotFoundError): + token_file(tmp_path / "missing")() + + empty = tmp_path / "empty" + empty.write_text(" \n") + with pytest.raises(ValueError, match="empty"): + token_file(str(empty))() + + monkeypatch.delenv("MY_JWT", raising=False) + with pytest.raises(ValueError, match="MY_JWT"): + token_env("MY_JWT")() + monkeypatch.setenv("MY_JWT", "") + with pytest.raises(ValueError, match="MY_JWT"): + token_env("MY_JWT")() + + +def test_token_env_reads_the_variable_on_every_call( + monkeypatch: pytest.MonkeyPatch, +) -> None: + provider = token_env("MY_JWT") + monkeypatch.setenv("MY_JWT", "assertion-1") + assert provider() == "assertion-1" + monkeypatch.setenv("MY_JWT", "assertion-2") + assert provider() == "assertion-2" + + +# --- the static key and the header overlay --------------------------------------------- + + +def test_static_key_credentials_never_change() -> None: + credentials = StaticKeyCredentials("sk_test_static") + + snapshot = credentials.resolve() + + assert dict(snapshot.headers) == {"Authorization": "Bearer sk_test_static"} + assert (snapshot.generation, snapshot.recoverable) == (0, False) + credentials.invalidate(0) + assert credentials.resolve() is snapshot + assert asyncio.run(credentials.aresolve()) is snapshot + assert "sk_test_static" not in repr(snapshot) + assert dict(StaticKeyCredentials(None).resolve().headers) == {} + + +def test_a_static_key_snapshot_leaves_the_request_headers_as_they_were() -> None: + client = WorkOSClient(api_key="sk_test_static") + headers = client._build_headers("post", "idem-1", None) + snapshot = client._request_credentials(None).resolve() + + applied = apply_snapshot(headers, snapshot) + + assert list(applied.items()) == list(headers.items()) + assert list(applied) == [ + "Content-Type", + "User-Agent", + "Authorization", + "Idempotency-Key", + ] + client.close() + + +def test_the_static_snapshot_follows_the_clients_current_key() -> None: + client = WorkOSClient(api_key="sk_test_before") + client._api_key = "sk_test_after" + + snapshot = client._request_credentials(None).resolve() + + assert snapshot.headers["Authorization"] == "Bearer sk_test_after" + client.close() + + +def test_snapshot_headers_replace_a_header_of_any_case() -> None: + snapshot = CredentialSnapshot( + headers={ + "Authorization": "Bearer new", + "x-url-environment-id": "environment_1", + }, + generation=3, + recoverable=True, + ) + headers = { + "authorization": "Bearer old", + "AUTHORIZATION": "Bearer older", + "X-Other": "1", + } + + applied = apply_snapshot(headers, snapshot) + + assert applied == { + "X-Other": "1", + "Authorization": "Bearer new", + "x-url-environment-id": "environment_1", + } + # The caller's dict is not modified; it is reused for the next attempt. + assert headers["authorization"] == "Bearer old" + + +def test_every_error_code_has_a_hint() -> None: + for code in ( + *OAUTH_CODES, + "exchange_failed", + "invalid_response", + "provider_failed", + "invalid_configuration", + ): + error = WorkloadIdentityError(code) + assert error.hint and error.hint != "The token endpoint rejected the exchange." + assert str(error) == f"{code}: {error.hint}" + assert WorkloadIdentityError("some_new_code").hint == ( + "The token endpoint rejected the exchange." + ) From 8840a7bb9be5a8101e748847fe1f28fbec8466dd Mon Sep 17 00:00:00 2001 From: "Garen J. Torikian" Date: Thu, 12 Nov 2026 01:18:17 -0800 Subject: [PATCH 02/24] feat(workload-identity): Add GitHub Actions, GCP and AWS identity token providers Three new distributions under packages/, each exporting one factory that takes an audience and returns an identity token provider for WorkloadIdentityCredentials: - workos-workload-identity-github-actions: github_actions(audience) - workos-workload-identity-gcp: gcp_metadata(audience) - workos-workload-identity-aws: aws_sts(audience, region=None) The GitHub Actions and GCP providers make one standard-library GET with a 10-second timeout and no redirects, and have no dependencies. The AWS provider calls STS GetWebIdentityToken (RS256) through boto3 on a regional endpoint. None of them depends on workos, and boto3 never becomes a dependency of the SDK. The repo becomes a uv workspace. The SDK gains `github-actions`, `gcp` and `aws` extras that pull in the matching distribution; installing one does not select it. The root wheel's contents are unchanged. CI: the nox `ci` session (and so scripts/ci) and a new `packages` job in ci.yml lint, type-check and test each distribution in an environment of its own. Root pytest is limited to tests/ so it does not collect them. Spec: docs/ideation/wif-backend-sdks/spec-phase-4.md --- .github/workflows/ci.yml | 38 +++ noxfile.py | 30 +++ .../workos-workload-identity-aws/CHANGELOG.md | 1 + packages/workos-workload-identity-aws/LICENSE | 21 ++ .../workos-workload-identity-aws/README.md | 32 +++ .../pyproject.toml | 25 ++ .../pyrightconfig.json | 4 + .../workos_workload_identity_aws/__init__.py | 98 ++++++++ .../src/workos_workload_identity_aws/py.typed | 0 .../tests/test_aws_sts.py | 193 +++++++++++++++ .../workos-workload-identity-gcp/CHANGELOG.md | 1 + packages/workos-workload-identity-gcp/LICENSE | 21 ++ .../workos-workload-identity-gcp/README.md | 30 +++ .../pyproject.toml | 25 ++ .../pyrightconfig.json | 4 + .../workos_workload_identity_gcp/__init__.py | 92 +++++++ .../src/workos_workload_identity_gcp/py.typed | 0 .../tests/test_gcp_metadata.py | 180 ++++++++++++++ .../CHANGELOG.md | 1 + .../LICENSE | 21 ++ .../README.md | 32 +++ .../pyproject.toml | 25 ++ .../pyrightconfig.json | 4 + .../__init__.py | 119 +++++++++ .../py.typed | 0 .../tests/test_github_actions.py | 226 ++++++++++++++++++ pyproject.toml | 17 ++ scripts/ci | 4 + uv.lock | 211 ++++++++++++++++ 29 files changed, 1455 insertions(+) create mode 100644 packages/workos-workload-identity-aws/CHANGELOG.md create mode 100644 packages/workos-workload-identity-aws/LICENSE create mode 100644 packages/workos-workload-identity-aws/README.md create mode 100644 packages/workos-workload-identity-aws/pyproject.toml create mode 100644 packages/workos-workload-identity-aws/pyrightconfig.json create mode 100644 packages/workos-workload-identity-aws/src/workos_workload_identity_aws/__init__.py create mode 100644 packages/workos-workload-identity-aws/src/workos_workload_identity_aws/py.typed create mode 100644 packages/workos-workload-identity-aws/tests/test_aws_sts.py create mode 100644 packages/workos-workload-identity-gcp/CHANGELOG.md create mode 100644 packages/workos-workload-identity-gcp/LICENSE create mode 100644 packages/workos-workload-identity-gcp/README.md create mode 100644 packages/workos-workload-identity-gcp/pyproject.toml create mode 100644 packages/workos-workload-identity-gcp/pyrightconfig.json create mode 100644 packages/workos-workload-identity-gcp/src/workos_workload_identity_gcp/__init__.py create mode 100644 packages/workos-workload-identity-gcp/src/workos_workload_identity_gcp/py.typed create mode 100644 packages/workos-workload-identity-gcp/tests/test_gcp_metadata.py create mode 100644 packages/workos-workload-identity-github-actions/CHANGELOG.md create mode 100644 packages/workos-workload-identity-github-actions/LICENSE create mode 100644 packages/workos-workload-identity-github-actions/README.md create mode 100644 packages/workos-workload-identity-github-actions/pyproject.toml create mode 100644 packages/workos-workload-identity-github-actions/pyrightconfig.json create mode 100644 packages/workos-workload-identity-github-actions/src/workos_workload_identity_github_actions/__init__.py create mode 100644 packages/workos-workload-identity-github-actions/src/workos_workload_identity_github_actions/py.typed create mode 100644 packages/workos-workload-identity-github-actions/tests/test_github_actions.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 55b028d5..61b9ccf6 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -31,6 +31,44 @@ jobs: - name: Test run: uv run pytest + # Each provider distribution is released on its own, so it is linted, + # type-checked and tested on its own: only its dependencies are installed. + packages: + name: ${{ matrix.package }} (Python ${{ matrix.python }}) + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + package: + - workos-workload-identity-github-actions + - workos-workload-identity-gcp + - workos-workload-identity-aws + python: ["3.10", "3.11", "3.12", "3.13", "3.14"] + defaults: + run: + working-directory: packages/${{ matrix.package }} + steps: + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + - uses: astral-sh/setup-uv@11f9893b081a58869d3b5fccaea48c9e9e46f990 # v8.3.2 + with: + python-version: ${{ matrix.python }} + enable-cache: true + + - name: Install dependencies + run: uv sync --locked + + - name: Lint + run: uv run ruff check . + + - name: Type check + run: uv run pyright + + - name: Test + run: uv run pytest + + - name: Build + run: uv build --out-dir dist + smoke-test: name: Smoke test (Python ${{ matrix.python }}) if: "${{ github.event_name == 'pull_request' && contains(toJSON(github.event.pull_request.labels.*.name), 'autorelease: pending') }}" diff --git a/noxfile.py b/noxfile.py index 3c46b8c6..d313260e 100644 --- a/noxfile.py +++ b/noxfile.py @@ -7,6 +7,8 @@ from __future__ import annotations +from pathlib import Path + import nox from nox_uv import session @@ -22,6 +24,24 @@ # Default sessions to run nox.options.sessions = ["tests"] +ROOT = Path(__file__).parent + +# The provider distributions under packages/ (workload identity federation). +PACKAGES = sorted(path.parent.name for path in ROOT.glob("packages/*/pyproject.toml")) + + +def check_package(s: nox.Session, package: str) -> None: + """Lint, type-check and test one provider distribution. + + Each distribution is released on its own, so it is checked on its own: in + an environment that holds only its dependencies, not this session's. + """ + environment = str(ROOT / ".nox" / f"package-{package}") + env = {"UV_PROJECT_ENVIRONMENT": environment, "VIRTUAL_ENV": environment} + with s.chdir(ROOT / "packages" / package): + for command in (["ruff", "check", "."], ["pyright"], ["pytest"]): + s.run("uv", "run", "--locked", *command, env=env, external=True) + @session(python=PYTHON_VERSIONS, uv_groups=["test"]) def tests(s: nox.Session) -> None: @@ -64,9 +84,19 @@ def typecheck(s: nox.Session) -> None: def ci(s: nox.Session) -> None: """Run all CI checks (format, lint, typecheck, tests) for a single Python version. + Covers the SDK and then every provider distribution under packages/. This is useful for quick local validation before pushing. """ s.run("ruff", "format", "--check", ".") s.run("ruff", "check", ".") s.run("pyright") s.run("pytest") + for package in PACKAGES: + check_package(s, package) + + +@nox.session(venv_backend="none") +@nox.parametrize("package", PACKAGES) +def packages(s: nox.Session, package: str) -> None: + """Lint, type-check and test the provider distributions under packages/.""" + check_package(s, package) diff --git a/packages/workos-workload-identity-aws/CHANGELOG.md b/packages/workos-workload-identity-aws/CHANGELOG.md new file mode 100644 index 00000000..825c32f0 --- /dev/null +++ b/packages/workos-workload-identity-aws/CHANGELOG.md @@ -0,0 +1 @@ +# Changelog diff --git a/packages/workos-workload-identity-aws/LICENSE b/packages/workos-workload-identity-aws/LICENSE new file mode 100644 index 00000000..67f8e417 --- /dev/null +++ b/packages/workos-workload-identity-aws/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 WorkOS + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/workos-workload-identity-aws/README.md b/packages/workos-workload-identity-aws/README.md new file mode 100644 index 00000000..af49da1d --- /dev/null +++ b/packages/workos-workload-identity-aws/README.md @@ -0,0 +1,32 @@ +# workos-workload-identity-aws + +AWS identity token provider for [WorkOS](https://workos.com) workload identity federation. It lets a workload on AWS call the WorkOS API without a stored API key: a token from AWS STS (`GetWebIdentityToken`) is exchanged for a short-lived WorkOS access token. + +This package depends on `boto3` and does not depend on `workos`. + +## Install + +```bash +pip install workos workos-workload-identity-aws +# or: pip install "workos[aws]" +``` + +## Use + +The calling identity needs the `sts:GetWebIdentityToken` permission, and outbound identity federation must be enabled for the AWS account. + +```python +from workos import WorkOSClient, WorkloadIdentityCredentials +from workos_workload_identity_aws import aws_sts + +client = WorkOSClient( + credentials=WorkloadIdentityCredentials( + client_id="client_...", + token_url="https://.../oauth2/token", + environment_id="environment_...", + identity_token_provider=aws_sts("https://api.workos.com", region="us-east-1"), + ) +) +``` + +`aws_sts(audience, region=None)` builds one STS client from the default AWS credential chain and returns a callable that requests an `RS256` token on every call. `region` is optional when boto3 can resolve one (`AWS_DEFAULT_REGION` or the shared config file); with no region, `aws_sts` raises. The request always goes to the regional STS endpoint. The audience must match the audience of the trust rule on your WorkOS application. diff --git a/packages/workos-workload-identity-aws/pyproject.toml b/packages/workos-workload-identity-aws/pyproject.toml new file mode 100644 index 00000000..54557d04 --- /dev/null +++ b/packages/workos-workload-identity-aws/pyproject.toml @@ -0,0 +1,25 @@ +[project] +name = "workos-workload-identity-aws" +version = "0.0.0" +description = "AWS identity token provider for WorkOS workload identity federation" +readme = "README.md" +license = "MIT" +authors = [{ name = "WorkOS", email = "sdk@workos.com" }] +requires-python = ">=3.10" + +dependencies = ["boto3>=1.41,<2"] + +[project.urls] +Homepage = "https://workos.com/docs/sdks/python" +Source = "https://github.com/workos/workos-python/tree/main/packages/workos-workload-identity-aws" +Changelog = "https://github.com/workos/workos-python/blob/main/packages/workos-workload-identity-aws/CHANGELOG.md" + +[dependency-groups] +dev = ["pytest~=9.0", "ruff~=0.15", "pyright~=1.1", "types-boto3[sts]>=1.41,<2"] + +[tool.pytest.ini_options] +testpaths = ["tests"] + +[build-system] +requires = ["uv_build~=0.11"] +build-backend = "uv_build" diff --git a/packages/workos-workload-identity-aws/pyrightconfig.json b/packages/workos-workload-identity-aws/pyrightconfig.json new file mode 100644 index 00000000..e472c336 --- /dev/null +++ b/packages/workos-workload-identity-aws/pyrightconfig.json @@ -0,0 +1,4 @@ +{ + "include": ["src", "tests"], + "typeCheckingMode": "strict" +} diff --git a/packages/workos-workload-identity-aws/src/workos_workload_identity_aws/__init__.py b/packages/workos-workload-identity-aws/src/workos_workload_identity_aws/__init__.py new file mode 100644 index 00000000..7e9baf0f --- /dev/null +++ b/packages/workos-workload-identity-aws/src/workos_workload_identity_aws/__init__.py @@ -0,0 +1,98 @@ +# @oagen-ignore-file + +"""AWS identity token provider for WorkOS workload identity federation. + +``aws_sts(audience, region)`` returns a callable that asks AWS STS +(``GetWebIdentityToken``) for a JWT representing the calling AWS identity. Pass +it to ``workos.WorkloadIdentityCredentials(identity_token_provider=...)``. + +The provider keeps no cache and does no retries; the WorkOS SDK retries the +call as part of the token exchange. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Callable, Optional + +import boto3 +import botocore.session +from botocore.exceptions import BotoCoreError, ClientError + +if TYPE_CHECKING: + from types_boto3_sts.client import STSClient + +__all__ = ["AwsStsProviderError", "aws_sts"] + +_SIGNING_ALGORITHM = "RS256" +_GLOBAL_ENDPOINT_HOSTS = ("sts.amazonaws.com",) + + +class AwsStsProviderError(Exception): + """AWS STS did not return a web identity token.""" + + +def _create_sts_client(region: Optional[str]) -> "STSClient": + """Build an STS client on the regional endpoint for ``region``. + + Credentials come from the AWS SDK's default chain. The region is the + argument, else whatever boto3 resolves (``AWS_DEFAULT_REGION`` or the + shared config file). + """ + core_session = botocore.session.get_session() + # GetWebIdentityToken is not served by the global endpoint. Force the + # regional one even when AWS_STS_REGIONAL_ENDPOINTS=legacy is set. + core_session.set_config_variable("sts_regional_endpoints", "regional") + session = boto3.Session(botocore_session=core_session) + resolved = region or session.region_name + if not resolved: + raise AwsStsProviderError( + "No AWS region is configured. Pass region to aws_sts() or set " + "AWS_DEFAULT_REGION; sts:GetWebIdentityToken needs a regional STS " + "endpoint." + ) + # The stubs type every service's client; only the STS one is installed. + client: STSClient = session.client("sts", region_name=resolved) # pyright: ignore[reportUnknownMemberType] + endpoint = client.meta.endpoint_url + if any(endpoint.endswith(f"//{host}") for host in _GLOBAL_ENDPOINT_HOSTS): + raise AwsStsProviderError( + f"AWS region {resolved!r} resolves to the global STS endpoint; " + "sts:GetWebIdentityToken needs a regional STS endpoint." + ) + return client + + +def aws_sts(audience: str, region: Optional[str] = None) -> Callable[[], str]: + """Return a provider of AWS STS web identity tokens for ``audience``. + + The calling identity needs the ``sts:GetWebIdentityToken`` permission, and + outbound identity federation must be enabled for the account. The + conventional audience is ``https://api.workos.com``. + + Raises ``AwsStsProviderError`` here, not on first use, when no region can + be resolved. + """ + if not audience: + raise ValueError("audience is required") + # Built once; the provider reuses it on every call. + client = _create_sts_client(region) + + def provider() -> str: + try: + response = client.get_web_identity_token( + Audience=[audience], SigningAlgorithm=_SIGNING_ALGORITHM + ) + except ClientError as exc: + code = exc.response.get("Error", {}).get("Code") or "UnknownError" + raise AwsStsProviderError( + f"sts:GetWebIdentityToken failed with {code}." + ) from None + except BotoCoreError as exc: + raise AwsStsProviderError( + f"sts:GetWebIdentityToken failed with {type(exc).__name__}." + ) from None + token = response.get("WebIdentityToken") + if not token: + raise AwsStsProviderError("sts:GetWebIdentityToken returned no token.") + return token + + return provider diff --git a/packages/workos-workload-identity-aws/src/workos_workload_identity_aws/py.typed b/packages/workos-workload-identity-aws/src/workos_workload_identity_aws/py.typed new file mode 100644 index 00000000..e69de29b diff --git a/packages/workos-workload-identity-aws/tests/test_aws_sts.py b/packages/workos-workload-identity-aws/tests/test_aws_sts.py new file mode 100644 index 00000000..661585f9 --- /dev/null +++ b/packages/workos-workload-identity-aws/tests/test_aws_sts.py @@ -0,0 +1,193 @@ +# @oagen-ignore-file + +"""Conformance cases WIF-AWS-01 and WIF-AWS-02. + +The STS client is the real boto3 client with a botocore ``Stubber`` attached, +so parameter names are validated against the service model and no request +leaves the process. +""" + +from __future__ import annotations + +import datetime +from pathlib import Path +from typing import TYPE_CHECKING, Callable, List, Optional + +import pytest +from botocore.stub import Stubber + +import workos_workload_identity_aws as aws +from workos_workload_identity_aws import AwsStsProviderError, aws_sts + +if TYPE_CHECKING: + from types_boto3_sts.client import STSClient + +AUDIENCE = "https://api.workos.com" +EXPECTED_PARAMS = {"Audience": [AUDIENCE], "SigningAlgorithm": "RS256"} + + +@pytest.fixture(autouse=True) +def isolated_aws_env(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + """No region, profile or config from the machine running the tests.""" + for name in ( + "AWS_REGION", + "AWS_DEFAULT_REGION", + "AWS_PROFILE", + "AWS_DEFAULT_PROFILE", + "AWS_STS_REGIONAL_ENDPOINTS", + "AWS_ENDPOINT_URL", + "AWS_ENDPOINT_URL_STS", + ): + monkeypatch.delenv(name, raising=False) + empty = tmp_path / "aws-empty" + empty.write_text("") + monkeypatch.setenv("AWS_CONFIG_FILE", str(empty)) + monkeypatch.setenv("AWS_SHARED_CREDENTIALS_FILE", str(empty)) + monkeypatch.setenv("AWS_EC2_METADATA_DISABLED", "true") + monkeypatch.setenv("AWS_ACCESS_KEY_ID", "test-access-key") + monkeypatch.setenv("AWS_SECRET_ACCESS_KEY", "test-secret-key") + + +class StubbedSts: + """Wraps the provider's client builder so each built client is stubbed.""" + + def __init__(self, monkeypatch: pytest.MonkeyPatch) -> None: + self.clients: List["STSClient"] = [] + self.stubbers: List[Stubber] = [] + self._queue: List[Callable[[Stubber], None]] = [] + real_create = aws._create_sts_client # pyright: ignore[reportPrivateUsage] + + def create(region: Optional[str]) -> "STSClient": + client = real_create(region) + stubber = Stubber(client) + for add in self._queue: + add(stubber) + stubber.activate() + self.clients.append(client) + self.stubbers.append(stubber) + return client + + monkeypatch.setattr(aws, "_create_sts_client", create) + + def returns(self, token: str) -> None: + self._queue.append( + lambda stubber: stubber.add_response( + "get_web_identity_token", + { + "WebIdentityToken": token, + "Expiration": datetime.datetime( + 2030, 1, 1, tzinfo=datetime.timezone.utc + ), + }, + EXPECTED_PARAMS, + ) + ) + + def fails(self, code: str, message: str, status: int) -> None: + self._queue.append( + lambda stubber: stubber.add_client_error( + "get_web_identity_token", + service_error_code=code, + service_message=message, + http_status_code=status, + expected_params=EXPECTED_PARAMS, + ) + ) + + +@pytest.fixture +def sts(monkeypatch: pytest.MonkeyPatch) -> StubbedSts: + return StubbedSts(monkeypatch) + + +def test_WIF_AWS_01_calls_get_web_identity_token_on_a_regional_endpoint( + sts: StubbedSts, +) -> None: + sts.returns("aws-jwt") + + provider = aws_sts(AUDIENCE, region="us-east-1") + + assert provider() == "aws-jwt" + # The stubber rejects any call whose parameters differ from EXPECTED_PARAMS: + # one call, audience https://api.workos.com, signing algorithm RS256. + sts.stubbers[0].assert_no_pending_responses() + assert len(sts.clients) == 1 + client = sts.clients[0] + assert client.meta.region_name == "us-east-1" + assert client.meta.endpoint_url == "https://sts.us-east-1.amazonaws.com" + + +def test_WIF_AWS_01_builds_the_client_once(sts: StubbedSts) -> None: + sts.returns("aws-jwt-1") + sts.returns("aws-jwt-2") + + provider = aws_sts(AUDIENCE, region="eu-west-1") + + assert [provider(), provider()] == ["aws-jwt-1", "aws-jwt-2"] + assert len(sts.clients) == 1 + assert sts.clients[0].meta.endpoint_url == "https://sts.eu-west-1.amazonaws.com" + + +def test_WIF_AWS_01_stays_regional_under_the_legacy_endpoint_setting( + sts: StubbedSts, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setenv("AWS_STS_REGIONAL_ENDPOINTS", "legacy") + + aws_sts(AUDIENCE, region="us-east-1") + + assert sts.clients[0].meta.endpoint_url == "https://sts.us-east-1.amazonaws.com" + + +def test_WIF_AWS_01_region_falls_back_to_what_the_aws_sdk_resolves( + sts: StubbedSts, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setenv("AWS_DEFAULT_REGION", "ap-southeast-2") + + aws_sts(AUDIENCE) + + assert sts.clients[0].meta.region_name == "ap-southeast-2" + assert ( + sts.clients[0].meta.endpoint_url == "https://sts.ap-southeast-2.amazonaws.com" + ) + + +def test_WIF_AWS_01_no_region_is_an_error_at_construction() -> None: + with pytest.raises(AwsStsProviderError, match="region"): + aws_sts(AUDIENCE) + + +def test_WIF_AWS_01_the_global_endpoint_is_rejected() -> None: + with pytest.raises(AwsStsProviderError, match="regional"): + aws_sts(AUDIENCE, region="aws-global") + + +def test_WIF_AWS_02_sts_error_names_the_call_and_the_code(sts: StubbedSts) -> None: + sts.fails( + "AccessDenied", + "User: arn:aws:iam::123456789012:role/app is not authorized to perform: " + "sts:GetWebIdentityToken", + 403, + ) + provider = aws_sts(AUDIENCE, region="us-east-1") + + with pytest.raises(AwsStsProviderError) as excinfo: + provider() + + message = str(excinfo.value) + assert "sts:GetWebIdentityToken" in message + assert "AccessDenied" in message + assert "aws-jwt" not in message + assert "aws-jwt" not in repr(excinfo.value) + + +def test_WIF_AWS_02_missing_token_in_the_response_is_an_error(sts: StubbedSts) -> None: + sts.returns("") + provider = aws_sts(AUDIENCE, region="us-east-1") + + with pytest.raises(AwsStsProviderError, match="sts:GetWebIdentityToken"): + provider() + + +def test_audience_is_required() -> None: + with pytest.raises(ValueError): + aws_sts("", region="us-east-1") diff --git a/packages/workos-workload-identity-gcp/CHANGELOG.md b/packages/workos-workload-identity-gcp/CHANGELOG.md new file mode 100644 index 00000000..825c32f0 --- /dev/null +++ b/packages/workos-workload-identity-gcp/CHANGELOG.md @@ -0,0 +1 @@ +# Changelog diff --git a/packages/workos-workload-identity-gcp/LICENSE b/packages/workos-workload-identity-gcp/LICENSE new file mode 100644 index 00000000..67f8e417 --- /dev/null +++ b/packages/workos-workload-identity-gcp/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 WorkOS + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/workos-workload-identity-gcp/README.md b/packages/workos-workload-identity-gcp/README.md new file mode 100644 index 00000000..f4948f32 --- /dev/null +++ b/packages/workos-workload-identity-gcp/README.md @@ -0,0 +1,30 @@ +# workos-workload-identity-gcp + +GCP identity token provider for [WorkOS](https://workos.com) workload identity federation. It lets a workload on GCP (Compute Engine, GKE, Cloud Run, Cloud Functions) call the WorkOS API without a stored API key: the service account's identity token is exchanged for a short-lived WorkOS access token. + +This package has no dependencies and does not depend on `workos`. + +## Install + +```bash +pip install workos workos-workload-identity-gcp +# or: pip install "workos[gcp]" +``` + +## Use + +```python +from workos import WorkOSClient, WorkloadIdentityCredentials +from workos_workload_identity_gcp import gcp_metadata + +client = WorkOSClient( + credentials=WorkloadIdentityCredentials( + client_id="client_...", + token_url="https://.../oauth2/token", + environment_id="environment_...", + identity_token_provider=gcp_metadata("https://api.workos.com"), + ) +) +``` + +`gcp_metadata(audience)` returns a callable that requests an identity token for the default service account from the metadata server on every call. The audience must match the audience of the trust rule on your WorkOS application. diff --git a/packages/workos-workload-identity-gcp/pyproject.toml b/packages/workos-workload-identity-gcp/pyproject.toml new file mode 100644 index 00000000..bc95e7af --- /dev/null +++ b/packages/workos-workload-identity-gcp/pyproject.toml @@ -0,0 +1,25 @@ +[project] +name = "workos-workload-identity-gcp" +version = "0.0.0" +description = "GCP identity token provider for WorkOS workload identity federation" +readme = "README.md" +license = "MIT" +authors = [{ name = "WorkOS", email = "sdk@workos.com" }] +requires-python = ">=3.10" + +dependencies = [] + +[project.urls] +Homepage = "https://workos.com/docs/sdks/python" +Source = "https://github.com/workos/workos-python/tree/main/packages/workos-workload-identity-gcp" +Changelog = "https://github.com/workos/workos-python/blob/main/packages/workos-workload-identity-gcp/CHANGELOG.md" + +[dependency-groups] +dev = ["pytest~=9.0", "ruff~=0.15", "pyright~=1.1"] + +[tool.pytest.ini_options] +testpaths = ["tests"] + +[build-system] +requires = ["uv_build~=0.11"] +build-backend = "uv_build" diff --git a/packages/workos-workload-identity-gcp/pyrightconfig.json b/packages/workos-workload-identity-gcp/pyrightconfig.json new file mode 100644 index 00000000..e472c336 --- /dev/null +++ b/packages/workos-workload-identity-gcp/pyrightconfig.json @@ -0,0 +1,4 @@ +{ + "include": ["src", "tests"], + "typeCheckingMode": "strict" +} diff --git a/packages/workos-workload-identity-gcp/src/workos_workload_identity_gcp/__init__.py b/packages/workos-workload-identity-gcp/src/workos_workload_identity_gcp/__init__.py new file mode 100644 index 00000000..b0f6e036 --- /dev/null +++ b/packages/workos-workload-identity-gcp/src/workos_workload_identity_gcp/__init__.py @@ -0,0 +1,92 @@ +# @oagen-ignore-file + +"""GCP identity token provider for WorkOS workload identity federation. + +``gcp_metadata(audience)`` returns a callable that asks the GCP metadata server +for the default service account's identity token for that audience. Pass it to +``workos.WorkloadIdentityCredentials(identity_token_provider=...)``. + +The provider keeps no cache and does no retries; the WorkOS SDK retries the +call as part of the token exchange. +""" + +from __future__ import annotations + +import urllib.error +import urllib.parse +import urllib.request +from email.message import Message +from typing import IO, Callable + +__all__ = ["GcpMetadataProviderError", "gcp_metadata"] + +_TIMEOUT_SECONDS = 10.0 +_IDENTITY_PATH = "/computeMetadata/v1/instance/service-accounts/default/identity" + +# Tests point this at a local mock. It is not a public option and is never read +# from the environment. +_METADATA_BASE_URL = "http://metadata.google.internal" + + +class GcpMetadataProviderError(Exception): + """The GCP metadata server did not return an identity token.""" + + +class _NoRedirect(urllib.request.HTTPRedirectHandler): + """Turns every redirect into an ``HTTPError`` instead of following it.""" + + def redirect_request( + self, + req: urllib.request.Request, + fp: IO[bytes], + code: int, + msg: str, + headers: Message, + newurl: str, + ) -> None: + return None + + +def gcp_metadata(audience: str) -> Callable[[], str]: + """Return a provider of GCP metadata-server identity tokens for ``audience``. + + The conventional audience is ``https://api.workos.com``. + """ + if not audience: + raise ValueError("audience is required") + query = f"audience={urllib.parse.quote(audience, safe='')}&format=full" + # The metadata server is link-local. The request never goes through a + # proxy named in the environment, which could not reach it or would answer + # with its own identity. + opener = urllib.request.build_opener(_NoRedirect, urllib.request.ProxyHandler({})) + + def provider() -> str: + request = urllib.request.Request( + f"{_METADATA_BASE_URL}{_IDENTITY_PATH}?{query}", + headers={"Metadata-Flavor": "Google"}, + method="GET", + ) + try: + with opener.open(request, timeout=_TIMEOUT_SECONDS) as response: + status: int = response.status + body: bytes = response.read() + except urllib.error.HTTPError as exc: + exc.close() + raise GcpMetadataProviderError( + f"GCP metadata identity request failed with status {exc.code}." + ) from None + except OSError as exc: + raise GcpMetadataProviderError( + f"GCP metadata identity request failed: {type(exc).__name__}." + ) from None + if status != 200: + raise GcpMetadataProviderError( + f"GCP metadata identity request failed with status {status}." + ) + + token = body.decode("utf-8", errors="replace").strip() + if not token: + raise GcpMetadataProviderError("GCP metadata identity response was empty.") + return token + + return provider diff --git a/packages/workos-workload-identity-gcp/src/workos_workload_identity_gcp/py.typed b/packages/workos-workload-identity-gcp/src/workos_workload_identity_gcp/py.typed new file mode 100644 index 00000000..e69de29b diff --git a/packages/workos-workload-identity-gcp/tests/test_gcp_metadata.py b/packages/workos-workload-identity-gcp/tests/test_gcp_metadata.py new file mode 100644 index 00000000..70f0b2b7 --- /dev/null +++ b/packages/workos-workload-identity-gcp/tests/test_gcp_metadata.py @@ -0,0 +1,180 @@ +# @oagen-ignore-file + +"""Conformance cases WIF-GCP-01 and WIF-GCP-02, against a local mock server.""" + +from __future__ import annotations + +import http.server +import threading +from dataclasses import dataclass, field +from typing import Dict, Iterator, List + +import pytest + +import workos_workload_identity_gcp as gcp +from workos_workload_identity_gcp import GcpMetadataProviderError, gcp_metadata + +AUDIENCE = "https://api.workos.com" +IDENTITY_PATH = "/computeMetadata/v1/instance/service-accounts/default/identity" + + +@dataclass +class Recorded: + method: str + path: str + headers: Dict[str, str] + + +@dataclass +class MockServer: + """A loopback HTTP server that records requests and returns a canned reply.""" + + status: int = 200 + body: bytes = b"" + reply_headers: Dict[str, str] = field(default_factory=lambda: {}) + requests: List[Recorded] = field(default_factory=lambda: []) + + def __post_init__(self) -> None: + mock = self + + class Handler(http.server.BaseHTTPRequestHandler): + def do_GET(self) -> None: + mock.requests.append( + Recorded( + "GET", + self.path, + {k.lower(): v for k, v in self.headers.items()}, + ) + ) + self.send_response(mock.status) + for name, value in mock.reply_headers.items(): + self.send_header(name, value) + self.send_header("Content-Length", str(len(mock.body))) + self.end_headers() + self.wfile.write(mock.body) + + def log_message(self, format: str, *args: object) -> None: + return None + + self._server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) + self._thread = threading.Thread( + target=self._server.serve_forever, + kwargs={"poll_interval": 0.01}, + daemon=True, + ) + self._thread.start() + + @property + def url(self) -> str: + return f"http://127.0.0.1:{self._server.server_address[1]}" + + def close(self) -> None: + self._server.shutdown() + self._server.server_close() + self._thread.join() + + +@pytest.fixture +def mock(monkeypatch: pytest.MonkeyPatch) -> Iterator[MockServer]: + """The metadata server. The provider's internal base URL points at it.""" + server = MockServer(body=b"gcp-jwt\n") + monkeypatch.setattr(gcp, "_METADATA_BASE_URL", server.url) + yield server + server.close() + + +@pytest.fixture +def second_mock() -> Iterator[MockServer]: + server = MockServer(body=b"redirected-jwt") + yield server + server.close() + + +def test_WIF_GCP_01_requests_identity_with_audience_and_metadata_header( + mock: MockServer, +) -> None: + provider = gcp_metadata(AUDIENCE) + + assert provider() == "gcp-jwt" + + assert len(mock.requests) == 1 + request = mock.requests[0] + assert request.method == "GET" + path, _, query = request.path.partition("?") + assert path == IDENTITY_PATH + assert query == "audience=https%3A%2F%2Fapi.workos.com&format=full" + assert request.headers["metadata-flavor"] == "Google" + + +def test_WIF_GCP_01_default_base_url_is_the_metadata_server() -> None: + assert gcp._METADATA_BASE_URL == "http://metadata.google.internal" # pyright: ignore[reportPrivateUsage] + + +def test_WIF_GCP_02_non_200_is_an_error(mock: MockServer) -> None: + mock.status = 404 + mock.body = b"not found" + + with pytest.raises(GcpMetadataProviderError, match="404"): + gcp_metadata(AUDIENCE)() + + assert len(mock.requests) == 1 + + +@pytest.mark.parametrize("body", [b"", b" \n\t "]) +def test_WIF_GCP_02_empty_body_is_an_error(mock: MockServer, body: bytes) -> None: + mock.body = body + + with pytest.raises(GcpMetadataProviderError, match="empty"): + gcp_metadata(AUDIENCE)() + + +def test_WIF_GCP_02_redirect_is_not_followed( + mock: MockServer, second_mock: MockServer +) -> None: + mock.status = 302 + mock.reply_headers = {"Location": f"{second_mock.url}/elsewhere"} + + with pytest.raises(GcpMetadataProviderError, match="302"): + gcp_metadata(AUDIENCE)() + + assert len(mock.requests) == 1 + assert second_mock.requests == [] + + +def test_connection_failure_is_a_provider_error( + monkeypatch: pytest.MonkeyPatch, +) -> None: + server = MockServer() + unused = server.url + server.close() + monkeypatch.setattr(gcp, "_METADATA_BASE_URL", unused) + + with pytest.raises(GcpMetadataProviderError): + gcp_metadata(AUDIENCE)() + + +def test_the_request_does_not_go_through_an_environment_proxy( + mock: MockServer, monkeypatch: pytest.MonkeyPatch +) -> None: + # Nothing listens on the proxy's port: the call works only if it is direct. + for name in ("http_proxy", "HTTP_PROXY", "all_proxy", "ALL_PROXY"): + monkeypatch.setenv(name, "http://127.0.0.1:9") + for name in ("no_proxy", "NO_PROXY"): + monkeypatch.delenv(name, raising=False) + + assert gcp_metadata(AUDIENCE)() == "gcp-jwt" + + assert len(mock.requests) == 1 + + +def test_audience_is_percent_encoded(mock: MockServer) -> None: + gcp_metadata("api://workos/prod env")() + + assert mock.requests[0].path == ( + f"{IDENTITY_PATH}?audience=api%3A%2F%2Fworkos%2Fprod%20env&format=full" + ) + + +def test_audience_is_required() -> None: + with pytest.raises(ValueError): + gcp_metadata("") diff --git a/packages/workos-workload-identity-github-actions/CHANGELOG.md b/packages/workos-workload-identity-github-actions/CHANGELOG.md new file mode 100644 index 00000000..825c32f0 --- /dev/null +++ b/packages/workos-workload-identity-github-actions/CHANGELOG.md @@ -0,0 +1 @@ +# Changelog diff --git a/packages/workos-workload-identity-github-actions/LICENSE b/packages/workos-workload-identity-github-actions/LICENSE new file mode 100644 index 00000000..67f8e417 --- /dev/null +++ b/packages/workos-workload-identity-github-actions/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 WorkOS + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/workos-workload-identity-github-actions/README.md b/packages/workos-workload-identity-github-actions/README.md new file mode 100644 index 00000000..8ad64c1f --- /dev/null +++ b/packages/workos-workload-identity-github-actions/README.md @@ -0,0 +1,32 @@ +# workos-workload-identity-github-actions + +GitHub Actions identity token provider for [WorkOS](https://workos.com) workload identity federation. It lets a workflow call the WorkOS API without a stored API key: the job's OIDC token is exchanged for a short-lived WorkOS access token. + +This package has no dependencies and does not depend on `workos`. + +## Install + +```bash +pip install workos workos-workload-identity-github-actions +# or: pip install "workos[github-actions]" +``` + +## Use + +The job needs `permissions: id-token: write`. + +```python +from workos import WorkOSClient, WorkloadIdentityCredentials +from workos_workload_identity_github_actions import github_actions + +client = WorkOSClient( + credentials=WorkloadIdentityCredentials( + client_id="client_...", + token_url="https://.../oauth2/token", + environment_id="environment_...", + identity_token_provider=github_actions("https://api.workos.com"), + ) +) +``` + +`github_actions(audience)` returns a callable that requests a token from `ACTIONS_ID_TOKEN_REQUEST_URL` on every call. The audience must match the audience of the trust rule on your WorkOS application. diff --git a/packages/workos-workload-identity-github-actions/pyproject.toml b/packages/workos-workload-identity-github-actions/pyproject.toml new file mode 100644 index 00000000..73300421 --- /dev/null +++ b/packages/workos-workload-identity-github-actions/pyproject.toml @@ -0,0 +1,25 @@ +[project] +name = "workos-workload-identity-github-actions" +version = "0.0.0" +description = "GitHub Actions identity token provider for WorkOS workload identity federation" +readme = "README.md" +license = "MIT" +authors = [{ name = "WorkOS", email = "sdk@workos.com" }] +requires-python = ">=3.10" + +dependencies = [] + +[project.urls] +Homepage = "https://workos.com/docs/sdks/python" +Source = "https://github.com/workos/workos-python/tree/main/packages/workos-workload-identity-github-actions" +Changelog = "https://github.com/workos/workos-python/blob/main/packages/workos-workload-identity-github-actions/CHANGELOG.md" + +[dependency-groups] +dev = ["pytest~=9.0", "ruff~=0.15", "pyright~=1.1"] + +[tool.pytest.ini_options] +testpaths = ["tests"] + +[build-system] +requires = ["uv_build~=0.11"] +build-backend = "uv_build" diff --git a/packages/workos-workload-identity-github-actions/pyrightconfig.json b/packages/workos-workload-identity-github-actions/pyrightconfig.json new file mode 100644 index 00000000..e472c336 --- /dev/null +++ b/packages/workos-workload-identity-github-actions/pyrightconfig.json @@ -0,0 +1,4 @@ +{ + "include": ["src", "tests"], + "typeCheckingMode": "strict" +} diff --git a/packages/workos-workload-identity-github-actions/src/workos_workload_identity_github_actions/__init__.py b/packages/workos-workload-identity-github-actions/src/workos_workload_identity_github_actions/__init__.py new file mode 100644 index 00000000..811d69e3 --- /dev/null +++ b/packages/workos-workload-identity-github-actions/src/workos_workload_identity_github_actions/__init__.py @@ -0,0 +1,119 @@ +# @oagen-ignore-file + +"""GitHub Actions identity token provider for WorkOS workload identity federation. + +``github_actions(audience)`` returns a callable that asks the GitHub Actions +OIDC endpoint for a JWT issued for that audience. Pass it to +``workos.WorkloadIdentityCredentials(identity_token_provider=...)``. + +The provider keeps no cache and does no retries; the WorkOS SDK retries the +call as part of the token exchange. +""" + +from __future__ import annotations + +import json +import os +import urllib.error +import urllib.parse +import urllib.request +from email.message import Message +from typing import IO, Callable + +__all__ = ["GitHubActionsProviderError", "github_actions"] + +_TIMEOUT_SECONDS = 10.0 +_URL_ENV = "ACTIONS_ID_TOKEN_REQUEST_URL" +_TOKEN_ENV = "ACTIONS_ID_TOKEN_REQUEST_TOKEN" +_MISSING_ENV_MESSAGE = ( + "GitHub Actions did not provide an OIDC token endpoint. " + "Add `permissions: id-token: write` to the workflow or job." +) + + +class GitHubActionsProviderError(Exception): + """The GitHub Actions OIDC token could not be fetched.""" + + +class _NoRedirect(urllib.request.HTTPRedirectHandler): + """Turns every redirect into an ``HTTPError`` instead of following it.""" + + def redirect_request( + self, + req: urllib.request.Request, + fp: IO[bytes], + code: int, + msg: str, + headers: Message, + newurl: str, + ) -> None: + return None + + +_OPENER = urllib.request.build_opener(_NoRedirect) + + +def _with_audience(url: str, audience: str) -> str: + """Append ``audience`` to the URL's query string, keeping what is there.""" + parts = urllib.parse.urlsplit(url) + if parts.scheme not in ("http", "https"): + raise GitHubActionsProviderError(f"{_URL_ENV} must be an http or https URL.") + encoded = "audience=" + urllib.parse.quote(audience, safe="") + query = f"{parts.query}&{encoded}" if parts.query else encoded + return urllib.parse.urlunsplit(parts._replace(query=query)) + + +def github_actions(audience: str) -> Callable[[], str]: + """Return a provider of GitHub Actions OIDC tokens for ``audience``. + + The job needs ``permissions: id-token: write``. The conventional audience + is ``https://api.workos.com``. + """ + if not audience: + raise ValueError("audience is required") + + def provider() -> str: + # Both variables are read on every call; the runner may rotate them. + url = os.environ.get(_URL_ENV, "") + request_token = os.environ.get(_TOKEN_ENV, "") + if not url or not request_token: + raise GitHubActionsProviderError(_MISSING_ENV_MESSAGE) + + request = urllib.request.Request( + _with_audience(url, audience), + headers={ + "Authorization": f"Bearer {request_token}", + "Accept": "application/json", + }, + method="GET", + ) + try: + with _OPENER.open(request, timeout=_TIMEOUT_SECONDS) as response: + status: int = response.status + body: bytes = response.read() + except urllib.error.HTTPError as exc: + exc.close() + raise GitHubActionsProviderError( + f"GitHub Actions OIDC token request failed with status {exc.code}." + ) from None + except OSError as exc: + raise GitHubActionsProviderError( + f"GitHub Actions OIDC token request failed: {type(exc).__name__}." + ) from None + if status != 200: + raise GitHubActionsProviderError( + f"GitHub Actions OIDC token request failed with status {status}." + ) + + try: + payload = json.loads(body) + except ValueError: + payload = None + value = payload.get("value") if isinstance(payload, dict) else None # pyright: ignore[reportUnknownVariableType, reportUnknownMemberType] + if not isinstance(value, str) or not value: + raise GitHubActionsProviderError( + "GitHub Actions OIDC token response had no token value." + ) + return value + + return provider diff --git a/packages/workos-workload-identity-github-actions/src/workos_workload_identity_github_actions/py.typed b/packages/workos-workload-identity-github-actions/src/workos_workload_identity_github_actions/py.typed new file mode 100644 index 00000000..e69de29b diff --git a/packages/workos-workload-identity-github-actions/tests/test_github_actions.py b/packages/workos-workload-identity-github-actions/tests/test_github_actions.py new file mode 100644 index 00000000..56c179c6 --- /dev/null +++ b/packages/workos-workload-identity-github-actions/tests/test_github_actions.py @@ -0,0 +1,226 @@ +# @oagen-ignore-file + +"""Conformance cases WIF-GHA-01 and WIF-GHA-02, against a local mock endpoint.""" + +from __future__ import annotations + +import http.server +import threading +from dataclasses import dataclass, field +from typing import Dict, Iterator, List + +import pytest + +from workos_workload_identity_github_actions import ( + GitHubActionsProviderError, + github_actions, +) + +AUDIENCE = "https://api.workos.com" +REQUEST_TOKEN = "gha-request-token" + + +@dataclass +class Recorded: + method: str + path: str + headers: Dict[str, str] + + +@dataclass +class MockServer: + """A loopback HTTP server that records requests and returns a canned reply.""" + + status: int = 200 + body: bytes = b"" + reply_headers: Dict[str, str] = field(default_factory=lambda: {}) + requests: List[Recorded] = field(default_factory=lambda: []) + + def __post_init__(self) -> None: + mock = self + + class Handler(http.server.BaseHTTPRequestHandler): + def do_GET(self) -> None: + mock.requests.append( + Recorded( + "GET", + self.path, + {k.lower(): v for k, v in self.headers.items()}, + ) + ) + self.send_response(mock.status) + for name, value in mock.reply_headers.items(): + self.send_header(name, value) + self.send_header("Content-Length", str(len(mock.body))) + self.end_headers() + self.wfile.write(mock.body) + + def log_message(self, format: str, *args: object) -> None: + return None + + self._server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) + self._thread = threading.Thread( + target=self._server.serve_forever, + kwargs={"poll_interval": 0.01}, + daemon=True, + ) + self._thread.start() + + @property + def url(self) -> str: + return f"http://127.0.0.1:{self._server.server_address[1]}" + + def close(self) -> None: + self._server.shutdown() + self._server.server_close() + self._thread.join() + + +@pytest.fixture +def mock() -> Iterator[MockServer]: + server = MockServer(body=b'{"value": "gha-jwt"}') + yield server + server.close() + + +@pytest.fixture +def second_mock() -> Iterator[MockServer]: + server = MockServer(body=b'{"value": "redirected-jwt"}') + yield server + server.close() + + +@pytest.fixture +def actions_env(mock: MockServer, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv( + "ACTIONS_ID_TOKEN_REQUEST_URL", f"{mock.url}/token?api-version=2.0" + ) + monkeypatch.setenv("ACTIONS_ID_TOKEN_REQUEST_TOKEN", REQUEST_TOKEN) + + +@pytest.mark.usefixtures("actions_env") +def test_WIF_GHA_01_requests_token_with_audience_and_bearer(mock: MockServer) -> None: + provider = github_actions(AUDIENCE) + + assert provider() == "gha-jwt" + + assert len(mock.requests) == 1 + request = mock.requests[0] + assert request.method == "GET" + path, _, query = request.path.partition("?") + assert path == "/token" + # The existing query string is kept and the encoded audience is added to it. + assert query.split("&") == [ + "api-version=2.0", + "audience=https%3A%2F%2Fapi.workos.com", + ] + assert request.headers["authorization"] == f"Bearer {REQUEST_TOKEN}" + assert request.headers["accept"] == "application/json" + + +def test_WIF_GHA_01_adds_a_query_string_when_the_url_has_none( + mock: MockServer, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setenv("ACTIONS_ID_TOKEN_REQUEST_URL", f"{mock.url}/token") + monkeypatch.setenv("ACTIONS_ID_TOKEN_REQUEST_TOKEN", REQUEST_TOKEN) + + assert github_actions("api://workos/prod env")() == "gha-jwt" + + assert mock.requests[0].path == "/token?audience=api%3A%2F%2Fworkos%2Fprod%20env" + + +@pytest.mark.usefixtures("actions_env") +def test_WIF_GHA_01_reads_the_environment_on_every_call( + mock: MockServer, monkeypatch: pytest.MonkeyPatch +) -> None: + provider = github_actions(AUDIENCE) + provider() + monkeypatch.setenv("ACTIONS_ID_TOKEN_REQUEST_TOKEN", "rotated-request-token") + provider() + + assert [r.headers["authorization"] for r in mock.requests] == [ + f"Bearer {REQUEST_TOKEN}", + "Bearer rotated-request-token", + ] + + +@pytest.mark.usefixtures("actions_env") +@pytest.mark.parametrize( + "missing", ["ACTIONS_ID_TOKEN_REQUEST_URL", "ACTIONS_ID_TOKEN_REQUEST_TOKEN"] +) +@pytest.mark.parametrize("how", ["unset", "empty"]) +def test_WIF_GHA_02_missing_env_fails_with_the_permission_hint( + mock: MockServer, monkeypatch: pytest.MonkeyPatch, missing: str, how: str +) -> None: + if how == "unset": + monkeypatch.delenv(missing) + else: + monkeypatch.setenv(missing, "") + provider = github_actions(AUDIENCE) + + with pytest.raises(GitHubActionsProviderError) as excinfo: + provider() + + assert "permissions: id-token: write" in str(excinfo.value) + assert mock.requests == [] + + +@pytest.mark.usefixtures("actions_env") +def test_non_200_fails_naming_the_status(mock: MockServer) -> None: + mock.status = 404 + + with pytest.raises(GitHubActionsProviderError, match="404") as excinfo: + github_actions(AUDIENCE)() + + assert REQUEST_TOKEN not in str(excinfo.value) + assert REQUEST_TOKEN not in repr(excinfo.value) + + +@pytest.mark.usefixtures("actions_env") +@pytest.mark.parametrize( + "body", [b"", b"not json", b"[]", b"{}", b'{"value": ""}', b'{"value": 7}'] +) +def test_missing_or_empty_value_fails(mock: MockServer, body: bytes) -> None: + mock.body = body + + with pytest.raises(GitHubActionsProviderError, match="no token value"): + github_actions(AUDIENCE)() + + +@pytest.mark.usefixtures("actions_env") +def test_redirect_is_not_followed(mock: MockServer, second_mock: MockServer) -> None: + mock.status = 302 + mock.reply_headers = {"Location": f"{second_mock.url}/elsewhere"} + + with pytest.raises(GitHubActionsProviderError, match="302"): + github_actions(AUDIENCE)() + + assert len(mock.requests) == 1 + assert second_mock.requests == [] + + +def test_connection_failure_is_a_provider_error( + mock: MockServer, monkeypatch: pytest.MonkeyPatch +) -> None: + unused = mock.url + mock.close() + monkeypatch.setenv("ACTIONS_ID_TOKEN_REQUEST_URL", f"{unused}/token") + monkeypatch.setenv("ACTIONS_ID_TOKEN_REQUEST_TOKEN", REQUEST_TOKEN) + + with pytest.raises(GitHubActionsProviderError) as excinfo: + github_actions(AUDIENCE)() + + assert REQUEST_TOKEN not in str(excinfo.value) + + +def test_non_http_url_is_rejected(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("ACTIONS_ID_TOKEN_REQUEST_URL", "file:///etc/hostname") + monkeypatch.setenv("ACTIONS_ID_TOKEN_REQUEST_TOKEN", REQUEST_TOKEN) + + with pytest.raises(GitHubActionsProviderError, match="http or https"): + github_actions(AUDIENCE)() + + +def test_audience_is_required() -> None: + with pytest.raises(ValueError): + github_actions("") diff --git a/pyproject.toml b/pyproject.toml index 37c31f41..b2b6af91 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -14,6 +14,13 @@ dependencies = [ "typing_extensions~=4.0; python_version < '3.11'", ] +[project.optional-dependencies] +# Identity token providers for workload identity federation. Each is its own +# distribution; installing one does not select it. +github-actions = ["workos-workload-identity-github-actions>=0.1,<1"] +gcp = ["workos-workload-identity-gcp>=0.1,<1"] +aws = ["workos-workload-identity-aws>=0.1,<1"] + [project.urls] Homepage = "https://workos.com/docs/sdks/python" Documentation = "https://workos.com/docs/reference" @@ -41,6 +48,8 @@ docs = ["pdoc>=14", "pydoc-markdown>=4", "black~=26.3"] [tool.pytest.ini_options] asyncio_default_fixture_loop_scope = "function" +# The provider distributions under packages/ run their own tests. +testpaths = ["tests"] [tool.ruff.lint.per-file-ignores] "*/__init__.py" = ["F401", "F403"] @@ -52,6 +61,14 @@ max-complexity = 10 source-include = ["py.typed"] source-exclude = ["tests*"] +[tool.uv.workspace] +members = ["packages/*"] + +[tool.uv.sources] +workos-workload-identity-github-actions = { workspace = true } +workos-workload-identity-gcp = { workspace = true } +workos-workload-identity-aws = { workspace = true } + [tool.pyright] typeCheckingMode = "strict" include = ["workos"] diff --git a/scripts/ci b/scripts/ci index edfa1015..37239a1e 100755 --- a/scripts/ci +++ b/scripts/ci @@ -1,4 +1,8 @@ #!/usr/bin/env bash +# +# Run every CI check: format, lint, type check and tests for the SDK, then +# lint, type check and tests for each provider distribution under packages/. +# Both live in the nox "ci" session. set -e diff --git a/uv.lock b/uv.lock index e975b520..829785e4 100644 --- a/uv.lock +++ b/uv.lock @@ -6,6 +6,14 @@ resolution-markers = [ "python_full_version < '3.12' or sys_platform != 'emscripten'", ] +[manifest] +members = [ + "workos", + "workos-workload-identity-aws", + "workos-workload-identity-gcp", + "workos-workload-identity-github-actions", +] + [[package]] name = "anyio" version = "4.14.2" @@ -91,6 +99,43 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/b1/28/9dd29175c1db777e6189e2a0bb5f37101adf19c3e509b236c8920f778d0b/black-26.10.1-py3-none-any.whl", hash = "sha256:28842f9a8207cc1df6eb983a35a14c5a0dfcd603d214fe82d84bef552afd2e3a", size = 239267, upload-time = "2026-10-10T04:13:38.808Z" }, ] +[[package]] +name = "boto3" +version = "1.44.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "botocore" }, + { name = "jmespath" }, + { name = "s3transfer" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/91/02/d46523af0a933c35604e2bbb33e4ca8f69a00f9990af6d6b29ed84db64aa/boto3-1.44.1.tar.gz", hash = "sha256:c81dfdaab894cbcba78aa3773fe3fb27a13b576f49ff5552b91190072fc7dac0", size = 112740, upload-time = "2026-11-11T21:11:18.611Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/36/5a/8af6cf092d9212091b8fc9bbf559bd04916094883a3c79a2464e715a1adf/boto3-1.44.1-py3-none-any.whl", hash = "sha256:1342653b8af9dc89f182cb5c0dfd5fa10f430d757c0ebd00326c053a6270d2c4", size = 140152, upload-time = "2026-11-11T21:11:15.904Z" }, +] + +[[package]] +name = "botocore" +version = "1.44.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "jmespath" }, + { name = "python-dateutil" }, + { name = "urllib3" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/b1/61/07918ec258ab7131dd601cb1aaffcd7fa008fa8bb0143fd195ecc4b4435d/botocore-1.44.1.tar.gz", hash = "sha256:e71f6249be2a7324899ba81c5958ac1809a78498ea2c8f60e00fc0e62262ab83", size = 16596239, upload-time = "2026-11-11T21:11:12.562Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/4d/45/ea4a91a51d6cafd6a7f7b0b8b88767c6d7054dc588ffcb7d1e11e9402e69/botocore-1.44.1-py3-none-any.whl", hash = "sha256:7a741074a78e28187c88d9f7f91db18731ea91725455873d863ae63ea35e75f3", size = 16295147, upload-time = "2026-11-11T21:11:08.108Z" }, +] + +[[package]] +name = "botocore-stubs" +version = "1.43.126" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/8c/7a/717e3dec2e4721f76621ddb397b4035ec1aff0c174b80f5c439512a352e9/botocore_stubs-1.43.126.tar.gz", hash = "sha256:15b14ba9066f6eec50a5861407fede151b4395e986036c8d564f4b908835f820", size = 42882, upload-time = "2026-11-06T22:57:14.723Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/66/23/10b0f6ce12d3d85cfaf24d2e420f76e8e744970289e447d43846e51db32d/botocore_stubs-1.43.126-py3-none-any.whl", hash = "sha256:07f1b96c89d787b95ebf0cc5f22fc2b7f61c179e704c289b377505d8d61d5d49", size = 67248, upload-time = "2026-11-06T22:57:12.732Z" }, +] + [[package]] name = "certifi" version = "2025.11.12" @@ -725,6 +770,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/62/a1/3d680cbfd5f4b8f15abc1d571870c5fc3e594bb582bc3b64ea099db13e56/jinja2-3.1.6-py3-none-any.whl", hash = "sha256:85ece4451f492d0c13c5dd7c13a64681a86afae63a5f347908daf103ce6d2f67", size = 134899, upload-time = "2025-03-05T20:05:00.369Z" }, ] +[[package]] +name = "jmespath" +version = "1.1.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d3/59/322338183ecda247fb5d1763a6cbe46eff7222eaeebafd9fa65d4bf5cb11/jmespath-1.1.0.tar.gz", hash = "sha256:472c87d80f36026ae83c6ddd0f1d05d4e510134ed462851fd5f754c8c3cbb88d", size = 27377, upload-time = "2026-01-22T16:35:26.279Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/14/2f/967ba146e6d58cf6a652da73885f52fc68001525b4197effc174321d70b4/jmespath-1.1.0-py3-none-any.whl", hash = "sha256:a5663118de4908c91729bea0acadca56526eb2698e83de10cd116ae0f4e97c64", size = 20419, upload-time = "2026-01-22T16:35:24.919Z" }, +] + [[package]] name = "markdown2" version = "2.5.5" @@ -1064,6 +1118,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/9d/7a/d968e294073affff457b041c2be9868a40c1c71f4a35fcc1e45e5493067b/pytest_cov-7.1.0-py3-none-any.whl", hash = "sha256:a0461110b7865f9a271aa1b51e516c9a95de9d696734a2f71e3e78f46e1d4678", size = 22876, upload-time = "2026-03-21T20:11:14.438Z" }, ] +[[package]] +name = "python-dateutil" +version = "2.9.0.post0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "six" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/66/c0/0c8b6ad9f17a802ee498c46e004a0eb49bc148f2fd230864601a86dcf6db/python-dateutil-2.9.0.post0.tar.gz", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 342432, upload-time = "2024-03-01T18:36:20.211Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ec/57/56b9bcc3c9c6a792fcbaf139543cee77261f3651ca9da0c93f5c1221264b/python_dateutil-2.9.0.post0-py2.py3-none-any.whl", hash = "sha256:a8b2bc7bffae282281c8140a97d3aa9c14da0b136dfe83f850eea9a5f7470427", size = 229892, upload-time = "2024-03-01T18:36:18.57Z" }, +] + [[package]] name = "pytokens" version = "0.4.1" @@ -1207,6 +1273,27 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/15/e2/77be4fff062fa78d9b2a4dea85d14785dac5f1d0c1fb58ed52331f0ebe28/ruff-0.15.8-py3-none-win_arm64.whl", hash = "sha256:cf891fa8e3bb430c0e7fac93851a5978fc99c8fa2c053b57b118972866f8e5f2", size = 11048175, upload-time = "2026-03-26T18:40:01.06Z" }, ] +[[package]] +name = "s3transfer" +version = "0.19.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "botocore" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/49/c5/0a5ce655109cb96b8dfad36908a4e108d15f5dc2eff8fbc3146c4312e704/s3transfer-0.19.3.tar.gz", hash = "sha256:8326acc3d056d7f7b8a37110c7d2aea41f67e83f6ae79cd3b5fbcca34c726406", size = 166087, upload-time = "2026-10-19T19:19:49.751Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e2/a4/88f9e10498759121060b8050a1554753dfc04df39bbbcc7aad9ecc8d9440/s3transfer-0.19.3-py3-none-any.whl", hash = "sha256:24eb7535804306355e31c952a90022bf5b2f9d760f9a11062c7493a217c08553", size = 90252, upload-time = "2026-10-19T19:19:48.309Z" }, +] + +[[package]] +name = "six" +version = "1.17.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/94/e7/b2c673351809dca68a0e064b6af791aa332cf192da575fd474ed7d6f16a2/six-1.17.0.tar.gz", hash = "sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81", size = 34031, upload-time = "2024-12-04T17:35:28.174Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl", hash = "sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274", size = 11050, upload-time = "2024-12-04T17:35:26.475Z" }, +] + [[package]] name = "tomli" version = "2.3.0" @@ -1286,6 +1373,46 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/d4/84/021bbeb7edb990dd6875cb6ab08d32faaa49fec63453d863730260a01f9e/typeapi-2.3.0-py3-none-any.whl", hash = "sha256:576b7dcb94412e91c5cae107a393674f8f99c10a24beb8be2302e3fed21d5cc2", size = 26858, upload-time = "2025-10-23T13:44:09.833Z" }, ] +[[package]] +name = "types-boto3" +version = "1.44.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "botocore-stubs" }, + { name = "types-s3transfer" }, + { name = "typing-extensions", marker = "python_full_version < '3.12'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/76/3c/e92aba04cced7f34790d898bbccc0f53ad75bf0abfd3c1d9d7ba61e15294/types_boto3-1.44.1.tar.gz", hash = "sha256:7dc049ce1b23889ae6ddfaa1bdf29a8d70ab3699e2440225528aae5760ffe6a1", size = 105918, upload-time = "2026-11-11T23:42:23.816Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/da/40/04e0f690f0ee111c1e08b0eb239df7114a43c34c32b3eaa60b8e92ffab15/types_boto3-1.44.1-py3-none-any.whl", hash = "sha256:c45a79d31d655da461438220a7c0b997c740a9098d52f251dd05f013cbebc324", size = 71959, upload-time = "2026-11-11T23:42:17.595Z" }, +] + +[package.optional-dependencies] +sts = [ + { name = "types-boto3-sts" }, +] + +[[package]] +name = "types-boto3-sts" +version = "1.44.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "typing-extensions", marker = "python_full_version < '3.12'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/69/a4/aee5d57949a736ab1088093ac42eab692211ba583de789add1e1a3d5554f/types_boto3_sts-1.44.0.tar.gz", hash = "sha256:031f560aac8e37c08384591679ea8ac058a3994827b91dae45abf01791b7f127", size = 17009, upload-time = "2026-11-10T22:50:38.137Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/43/73/3a3b4831759bc2f3a01c5eedda3ec0769a834896ff5c7585e0efc3cf31a6/types_boto3_sts-1.44.0-py3-none-any.whl", hash = "sha256:d4c1085ca0a96eda6c2a7d72655fe67501462f3e297ad7f383cde4b3a9c76e7b", size = 21044, upload-time = "2026-11-10T22:50:36.689Z" }, +] + +[[package]] +name = "types-s3transfer" +version = "0.19.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/89/b2/4f2d72b5d234c81caa07dee688cacee2c8dc5bd793e9ae70a573f00d6425/types_s3transfer-0.19.3.tar.gz", hash = "sha256:99422ef028a5f854cd92d1e72cf4208bd0569f68a87936ca02fb9f91a68cdcd3", size = 13780, upload-time = "2026-10-20T02:24:19.016Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f5/98/972fa03c9a6e1cc9184a28ea0354af50a6764bb172fe2d0751798a295f07/types_s3transfer-0.19.3-py3-none-any.whl", hash = "sha256:6843143f3b79e3cb73e58b6f45738e28e88d9f681fd32cc5ef7fa16f0c193356", size = 19476, upload-time = "2026-10-20T02:24:17.682Z" }, +] + [[package]] name = "typing-extensions" version = "4.15.0" @@ -1362,6 +1489,17 @@ dependencies = [ { name = "typing-extensions", marker = "python_full_version < '3.11'" }, ] +[package.optional-dependencies] +aws = [ + { name = "workos-workload-identity-aws" }, +] +gcp = [ + { name = "workos-workload-identity-gcp" }, +] +github-actions = [ + { name = "workos-workload-identity-github-actions" }, +] + [package.dev-dependencies] dev = [ { name = "httpx" }, @@ -1402,7 +1540,11 @@ requires-dist = [ { name = "httpx2", specifier = "~=2.13" }, { name = "pyjwt", specifier = "~=2.12" }, { name = "typing-extensions", marker = "python_full_version < '3.11'", specifier = "~=4.0" }, + { name = "workos-workload-identity-aws", marker = "extra == 'aws'", editable = "packages/workos-workload-identity-aws" }, + { name = "workos-workload-identity-gcp", marker = "extra == 'gcp'", editable = "packages/workos-workload-identity-gcp" }, + { name = "workos-workload-identity-github-actions", marker = "extra == 'github-actions'", editable = "packages/workos-workload-identity-github-actions" }, ] +provides-extras = ["github-actions", "gcp", "aws"] [package.metadata.requires-dev] dev = [ @@ -1436,6 +1578,75 @@ type-check = [ { name = "pyright", specifier = "~=1.1" }, ] +[[package]] +name = "workos-workload-identity-aws" +version = "0.0.0" +source = { editable = "packages/workos-workload-identity-aws" } +dependencies = [ + { name = "boto3" }, +] + +[package.dev-dependencies] +dev = [ + { name = "pyright" }, + { name = "pytest" }, + { name = "ruff" }, + { name = "types-boto3", extra = ["sts"] }, +] + +[package.metadata] +requires-dist = [{ name = "boto3", specifier = ">=1.41,<2" }] + +[package.metadata.requires-dev] +dev = [ + { name = "pyright", specifier = "~=1.1" }, + { name = "pytest", specifier = "~=9.0" }, + { name = "ruff", specifier = "~=0.15" }, + { name = "types-boto3", extras = ["sts"], specifier = ">=1.41,<2" }, +] + +[[package]] +name = "workos-workload-identity-gcp" +version = "0.0.0" +source = { editable = "packages/workos-workload-identity-gcp" } + +[package.dev-dependencies] +dev = [ + { name = "pyright" }, + { name = "pytest" }, + { name = "ruff" }, +] + +[package.metadata] + +[package.metadata.requires-dev] +dev = [ + { name = "pyright", specifier = "~=1.1" }, + { name = "pytest", specifier = "~=9.0" }, + { name = "ruff", specifier = "~=0.15" }, +] + +[[package]] +name = "workos-workload-identity-github-actions" +version = "0.0.0" +source = { editable = "packages/workos-workload-identity-github-actions" } + +[package.dev-dependencies] +dev = [ + { name = "pyright" }, + { name = "pytest" }, + { name = "ruff" }, +] + +[package.metadata] + +[package.metadata.requires-dev] +dev = [ + { name = "pyright", specifier = "~=1.1" }, + { name = "pytest", specifier = "~=9.0" }, + { name = "ruff", specifier = "~=0.15" }, +] + [[package]] name = "wrapt" version = "2.1.2" From 860b2ebfa17210a65ebf51d84d3fa3ab9212d368 Mon Sep 17 00:00:00 2001 From: "Garen J. Torikian" Date: Thu, 12 Nov 2026 01:18:26 -0800 Subject: [PATCH 03/24] ci(workload-identity): Release each identity token provider on its own Turn the repo into a release-please manifest monorepo. The root entry is unchanged, so SDK tags stay vX.Y.Z and its release PR title stays "chore(main): release X.Y.Z". Each provider distribution gets an entry (release type python, starting at 0.0.0 so the first release is 0.1.0), its own release PR (separate-pull-requests), a tag of the form -vX.Y.Z, and a publish job gated on its own release. The release PR enrichment job assumed one release PR. It now runs once per PR: every release PR gets its uv.lock refreshed, because the one lockfile records each distribution's version, and changelog fragments are inlined only into the SDK's PR. A workspace member builds into the workspace root's dist/ by default, so the provider jobs build with --out-dir dist before uv publish. Written but not run: release-please cannot be exercised before merge. Before the first release, add a PyPI trusted publisher for each of the three distributions and rehearse the flow on a fork. Spec: docs/ideation/wif-backend-sdks/spec-phase-4.md --- .github/workflows/release-please.yml | 108 +++++++++++++++++++++++++-- .release-please-manifest.json | 5 +- release-please-config.json | 22 ++++++ 3 files changed, 128 insertions(+), 7 deletions(-) diff --git a/.github/workflows/release-please.yml b/.github/workflows/release-please.yml index b6c23759..5f2718cd 100644 --- a/.github/workflows/release-please.yml +++ b/.github/workflows/release-please.yml @@ -27,8 +27,15 @@ jobs: pull-requests: write outputs: pr: ${{ steps.release.outputs.pr }} + # Every release PR this run created or updated. The SDK and each provider + # distribution get their own (separate-pull-requests). + prs: ${{ steps.release.outputs.prs }} + # The unprefixed outputs are the root package's, i.e. the SDK's. release_created: ${{ steps.release.outputs.release_created }} tag_name: ${{ steps.release.outputs.tag_name }} + github_actions_release_created: ${{ steps.release.outputs['packages/workos-workload-identity-github-actions--release_created'] }} + gcp_release_created: ${{ steps.release.outputs['packages/workos-workload-identity-gcp--release_created'] }} + aws_release_created: ${{ steps.release.outputs['packages/workos-workload-identity-aws--release_created'] }} steps: - name: Generate token id: generate-token @@ -45,15 +52,20 @@ jobs: with: token: ${{ steps.generate-token.outputs.token }} - # While the release PR is open, enrich it before it merges. Runs as its - # own job (gated on the PR existing) so a failure here can never block the - # release or the PyPI publish that depends on release-please. + # While a release PR is open, enrich it before it merges. Runs as its + # own job (gated on a PR existing) so a failure here can never block the + # release or the PyPI publish that depends on release-please. One run per + # release PR: the SDK's and each provider distribution's. enrich-release-pr: needs: release-please if: needs.release-please.outputs.pr runs-on: ubuntu-latest permissions: contents: write + strategy: + fail-fast: false + matrix: + pr: ${{ fromJSON(needs.release-please.outputs.prs) }} steps: - name: Generate token id: generate-token @@ -67,12 +79,14 @@ jobs: - name: Checkout release PR branch uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: - ref: ${{ fromJSON(needs.release-please.outputs.pr).headBranchName }} + ref: ${{ matrix.pr.headBranchName }} token: ${{ steps.generate-token.outputs.token }} - name: Install uv uses: astral-sh/setup-uv@11f9893b081a58869d3b5fccaea48c9e9e46f990 # v8.3.2 + # Every release PR needs this: the one uv.lock at the root records the + # version of the SDK and of each provider distribution. - name: Update lockfile run: | uv lock @@ -89,9 +103,13 @@ jobs: # without a fragment (typical for human-authored PRs), keep what # release-please wrote. Fragments are deleted in the same commit. # Idempotent: if no fragments exist, skip silently. + # SDK release PR only. Fragments describe SDK changes and go into the + # root CHANGELOG.md; a provider's release PR is on a branch named + # ...--components--. - name: Inline rich changelog fragments + if: ${{ !contains(matrix.pr.headBranchName, '--components--') }} env: - PR_JSON: ${{ needs.release-please.outputs.pr }} + PR_TITLE: ${{ matrix.pr.title }} run: | set -euo pipefail shopt -s nullglob @@ -101,7 +119,7 @@ jobs: exit 0 fi - VERSION=$(echo "$PR_JSON" | jq -r '.title' | grep -oE '[0-9]+\.[0-9]+\.[0-9]+') + VERSION=$(echo "$PR_TITLE" | grep -oE '[0-9]+\.[0-9]+\.[0-9]+') export VERSION python3 - <<'PY' @@ -212,6 +230,9 @@ jobs: echo "No CHANGELOG.md body for $TAG; keeping release-please default notes." fi + # The SDK. In a uv workspace, `uv build` at the root builds only the root + # package; each provider distribution has its own job below, gated on its + # own release. publish: needs: release-please if: needs.release-please.outputs.release_created == 'true' @@ -231,3 +252,78 @@ jobs: - name: Publish to PyPI run: uv publish + + publish-workload-identity-github-actions: + needs: release-please + if: needs.release-please.outputs.github_actions_release_created == 'true' + runs-on: ubuntu-latest + permissions: + id-token: write + contents: read + defaults: + run: + working-directory: packages/workos-workload-identity-github-actions + steps: + - name: Checkout + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + + - name: Install uv + uses: astral-sh/setup-uv@11f9893b081a58869d3b5fccaea48c9e9e46f990 # v8.3.2 + + # A workspace member builds into the workspace root's dist/ by default; + # keep the artifacts next to the package so uv publish finds only them. + - name: Build + run: uv build --out-dir dist + + - name: Publish to PyPI + run: uv publish + + publish-workload-identity-gcp: + needs: release-please + if: needs.release-please.outputs.gcp_release_created == 'true' + runs-on: ubuntu-latest + permissions: + id-token: write + contents: read + defaults: + run: + working-directory: packages/workos-workload-identity-gcp + steps: + - name: Checkout + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + + - name: Install uv + uses: astral-sh/setup-uv@11f9893b081a58869d3b5fccaea48c9e9e46f990 # v8.3.2 + + # A workspace member builds into the workspace root's dist/ by default; + # keep the artifacts next to the package so uv publish finds only them. + - name: Build + run: uv build --out-dir dist + + - name: Publish to PyPI + run: uv publish + + publish-workload-identity-aws: + needs: release-please + if: needs.release-please.outputs.aws_release_created == 'true' + runs-on: ubuntu-latest + permissions: + id-token: write + contents: read + defaults: + run: + working-directory: packages/workos-workload-identity-aws + steps: + - name: Checkout + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + + - name: Install uv + uses: astral-sh/setup-uv@11f9893b081a58869d3b5fccaea48c9e9e46f990 # v8.3.2 + + # A workspace member builds into the workspace root's dist/ by default; + # keep the artifacts next to the package so uv publish finds only them. + - name: Build + run: uv build --out-dir dist + + - name: Publish to PyPI + run: uv publish diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 91e7ba5e..413ebadf 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,6 @@ { - ".": "10.8.0" + ".": "10.8.0", + "packages/workos-workload-identity-github-actions": "0.0.0", + "packages/workos-workload-identity-gcp": "0.0.0", + "packages/workos-workload-identity-aws": "0.0.0" } diff --git a/release-please-config.json b/release-please-config.json index e6a27508..31416c5a 100644 --- a/release-please-config.json +++ b/release-please-config.json @@ -1,10 +1,32 @@ { + "separate-pull-requests": true, "packages": { ".": { "release-type": "python", "bump-minor-pre-major": true, "bump-patch-for-minor-pre-major": true, "changelog-path": "CHANGELOG.md" + }, + "packages/workos-workload-identity-github-actions": { + "release-type": "python", + "component": "workos-workload-identity-github-actions", + "package-name": "workos-workload-identity-github-actions", + "include-component-in-tag": true, + "changelog-path": "CHANGELOG.md" + }, + "packages/workos-workload-identity-gcp": { + "release-type": "python", + "component": "workos-workload-identity-gcp", + "package-name": "workos-workload-identity-gcp", + "include-component-in-tag": true, + "changelog-path": "CHANGELOG.md" + }, + "packages/workos-workload-identity-aws": { + "release-type": "python", + "component": "workos-workload-identity-aws", + "package-name": "workos-workload-identity-aws", + "include-component-in-tag": true, + "changelog-path": "CHANGELOG.md" } }, "$schema": "https://raw.githubusercontent.com/googleapis/release-please/main/schemas/config.json" From ecee1e9c85b845e0994705d6db65cbd69c132092 Mon Sep 17 00:00:00 2001 From: "Garen J. Torikian" Date: Thu, 12 Nov 2026 01:18:26 -0800 Subject: [PATCH 04/24] docs(workload-identity): Document workload identity in the README Add a "Workload Identity" section: how to pass credentials, the settings and their environment variables, one example per platform provider, the built-in file and environment providers, a custom callback, and WorkloadIdentityError. Spec: docs/ideation/wif-backend-sdks/spec-phase-4.md --- README.md | 109 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 109 insertions(+) diff --git a/README.md b/README.md index c3213289..05b7b263 100644 --- a/README.md +++ b/README.md @@ -59,6 +59,115 @@ The client reads credentials from the environment when not passed explicitly: | `WORKOS_REQUEST_TIMEOUT` | HTTP timeout in seconds (defaults to `60`) | | `WORKOS_ISSUER` | Expected `iss` claim of session access tokens, comma-separated to accept several (not validated when unset; also settable via `jwt_issuer=`) | +## Workload Identity + +A workload running in GitHub Actions, GCP or AWS can call the WorkOS API without a stored API key. The SDK exchanges a JWT issued by the platform for a short-lived WorkOS access token, caches it in memory, and refreshes it before it expires. + +Build a `WorkloadIdentityCredentials` and pass it as `credentials` instead of `api_key`: + +```python +from workos import WorkOSClient, WorkloadIdentityCredentials +from workos_workload_identity_github_actions import github_actions + +client = WorkOSClient( + credentials=WorkloadIdentityCredentials( + client_id="client_1234", # the M2M application's client ID + token_url="https://.../oauth2/token", # the token exchange endpoint + environment_id="environment_1234", + identity_token_provider=github_actions("https://api.workos.com"), + ) +) + +page = client.organizations.list_organizations() +``` + +`AsyncWorkOSClient` takes the same `credentials` argument. Workload identity is used only when you pass `credentials`: no environment variable switches it on, `WORKOS_API_KEY` is ignored when credentials are passed, and a failed exchange is an error, never a fallback to an API key. Passing both `api_key` and `credentials` raises `ValueError`. + +| Argument | Environment variable | Description | +|----------|----------------------|-------------| +| `identity_token_provider` | | A callable that returns the workload's JWT (required) | +| `client_id` | `WORKOS_CLIENT_ID` | The M2M application's client ID (required) | +| `token_url` | `WORKOS_WIF_TOKEN_URL` | The token exchange endpoint (required; there is no default) | +| `environment_id` | `WORKOS_ENVIRONMENT_ID` | The environment ID, sent with every API request (required) | +| `resource` | | The resource to request a token for (defaults to `https://api.workos.com`) | +| `scope` | `WORKOS_WIF_SCOPE` | The scope to request (omitted when unset) | + +An explicit argument wins over its environment variable. + +### Platform Providers + +Each platform's provider is a separate distribution, so the SDK itself gains no dependencies. Install the one you need; installing a provider does not select it. + +```bash +pip install "workos[github-actions]" # workos-workload-identity-github-actions +pip install "workos[gcp]" # workos-workload-identity-gcp +pip install "workos[aws]" # workos-workload-identity-aws (depends on boto3) +``` + +Every provider takes the audience the identity token is requested for. It must match the audience of the trust rule on your WorkOS application; the conventional value is `https://api.workos.com`. + +**GitHub Actions.** The job needs `permissions: id-token: write`. + +```python +from workos_workload_identity_github_actions import github_actions + +provider = github_actions("https://api.workos.com") +``` + +**GCP.** Uses the default service account's identity token from the metadata server (Compute Engine, GKE, Cloud Run, Cloud Functions). + +```python +from workos_workload_identity_gcp import gcp_metadata + +provider = gcp_metadata("https://api.workos.com") +``` + +**AWS.** Calls STS `GetWebIdentityToken` with the default AWS credential chain. The calling identity needs the `sts:GetWebIdentityToken` permission. `region` is optional when boto3 can resolve one. + +```python +from workos_workload_identity_aws import aws_sts + +provider = aws_sts("https://api.workos.com", region="us-east-1") +``` + +### Custom Providers + +A provider is any callable that returns the JWT as a string. The SDK ships two, and you can pass your own function: + +```python +from workos import WorkloadIdentityCredentials, token_env, token_file + +# A file, read again on every exchange (for example a projected Kubernetes token) +provider = token_file("/var/run/secrets/tokens/workos") + +# An environment variable, read on every exchange +provider = token_env("MY_IDENTITY_TOKEN") + +# Your own callable +def provider() -> str: + return fetch_identity_token_somehow() + +# client_id, token_url and environment_id come from the environment here +credentials = WorkloadIdentityCredentials(identity_token_provider=provider) +``` + +With `AsyncWorkOSClient`, a plain function runs in a worker thread so it cannot block the event loop, and an `async def` provider is awaited. + +### Workload Identity Errors + +A failed exchange raises `WorkloadIdentityError`. Its `code` is the OAuth error code from the token endpoint (such as `invalid_grant`) or one of `exchange_failed`, `invalid_response`, `provider_failed` and `invalid_configuration`; `hint` says what to check; `description` carries the server's detail when there is any. Neither token ever appears in an error. + +```python +from workos import WorkloadIdentityError + +try: + client.organizations.list_organizations() +except WorkloadIdentityError as e: + print(e.code, e.hint) +``` + +The exchange is retried on connection failures, 429 and 5xx responses. If the API answers a request with a 401, the SDK discards that token, exchanges again, and retries the request once. + ## Available Resources The client exposes the WorkOS API through typed namespace properties: From ca29dee5ed43f2d890202265189b88f0a5abff78 Mon Sep 17 00:00:00 2001 From: "Garen J. Torikian" Date: Thu, 12 Nov 2026 05:21:58 -0800 Subject: [PATCH 05/24] ci(workload-identity): Start provider releases at 0.1.0 release-please does not treat a manifest version of 0.0.0 as a previous release, so with no tag yet it would release each provider distribution as 1.0.0. That is outside the `>=0.1,<1` range of the SDK's extras, and `pip install "workos[aws]"` could not resolve. Set initial-version so the first release is 0.1.0. Spec: docs/ideation/wif-backend-sdks/spec-phase-4.md --- release-please-config.json | 3 +++ 1 file changed, 3 insertions(+) diff --git a/release-please-config.json b/release-please-config.json index 31416c5a..7afdab8d 100644 --- a/release-please-config.json +++ b/release-please-config.json @@ -9,6 +9,7 @@ }, "packages/workos-workload-identity-github-actions": { "release-type": "python", + "initial-version": "0.1.0", "component": "workos-workload-identity-github-actions", "package-name": "workos-workload-identity-github-actions", "include-component-in-tag": true, @@ -16,6 +17,7 @@ }, "packages/workos-workload-identity-gcp": { "release-type": "python", + "initial-version": "0.1.0", "component": "workos-workload-identity-gcp", "package-name": "workos-workload-identity-gcp", "include-component-in-tag": true, @@ -23,6 +25,7 @@ }, "packages/workos-workload-identity-aws": { "release-type": "python", + "initial-version": "0.1.0", "component": "workos-workload-identity-aws", "package-name": "workos-workload-identity-aws", "include-component-in-tag": true, From a5db152850202c324c807c17fb02730b1a373b06 Mon Sep 17 00:00:00 2001 From: "Garen J. Torikian" Date: Thu, 12 Nov 2026 07:45:07 -0800 Subject: [PATCH 06/24] ci(workload-identity): Keep provider-only commits out of the SDK release release-please assigns the root package every commit, so a fix that touched only packages/* also opened an SDK release PR and appeared in the SDK changelog. Exclude packages/ on the root entry so that a provider-only commit releases only that provider. A commit that also changes a root file still reaches the SDK. In practice that is a provider dependency change, which rewrites the one uv.lock at the root. Spec: docs/ideation/wif-backend-sdks/spec-phase-4.md --- release-please-config.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/release-please-config.json b/release-please-config.json index 7afdab8d..d6fce603 100644 --- a/release-please-config.json +++ b/release-please-config.json @@ -5,7 +5,8 @@ "release-type": "python", "bump-minor-pre-major": true, "bump-patch-for-minor-pre-major": true, - "changelog-path": "CHANGELOG.md" + "changelog-path": "CHANGELOG.md", + "exclude-paths": ["packages"] }, "packages/workos-workload-identity-github-actions": { "release-type": "python", From 4a1bc7160d76b2f296fb23eb1a07b0f3c0c3c1cf Mon Sep 17 00:00:00 2001 From: "Garen J. Torikian" Date: Thu, 12 Nov 2026 07:48:11 -0800 Subject: [PATCH 07/24] ci(workload-identity): Bound the first provider release scan release-please gives an empty commit to every package, and for a package with no release yet it scans the last 500 commits. main has empty `Release-As:` commits in that range (the newest is 5c1faa3, `Release-As: 10.6.0`). A Release-As commit wins over initial-version, so each provider's first release would have been 10.6.0, not 0.1.0. Set bootstrap-sha to the v10.8.0 release commit so that scan stops there. release-please reads it only while a package has no release. Spec: docs/ideation/wif-backend-sdks/spec-phase-4.md --- release-please-config.json | 1 + 1 file changed, 1 insertion(+) diff --git a/release-please-config.json b/release-please-config.json index d6fce603..1eeb30be 100644 --- a/release-please-config.json +++ b/release-please-config.json @@ -1,5 +1,6 @@ { "separate-pull-requests": true, + "bootstrap-sha": "6ec552607b8f0358176fa9910b2b22f484fb21ed", "packages": { ".": { "release-type": "python", From 450a9b082831594ac878cd6147eefa8fb9ae7c78 Mon Sep 17 00:00:00 2001 From: "Garen J. Torikian" Date: Thu, 12 Nov 2026 12:42:25 -0800 Subject: [PATCH 08/24] test(workload-identity): Name the GCP proxy test for WIF-GCP-03 The rule that the GCP metadata request never goes through a proxy is now conformance case WIF-GCP-03. The conformance check reads case IDs from test names, so the existing test for the rule now carries the ID. No behavior changes. Spec: docs/ideation/wif-backend-sdks/spec-phase-4.md --- .../workos-workload-identity-gcp/tests/test_gcp_metadata.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/workos-workload-identity-gcp/tests/test_gcp_metadata.py b/packages/workos-workload-identity-gcp/tests/test_gcp_metadata.py index 70f0b2b7..815afa25 100644 --- a/packages/workos-workload-identity-gcp/tests/test_gcp_metadata.py +++ b/packages/workos-workload-identity-gcp/tests/test_gcp_metadata.py @@ -1,6 +1,6 @@ # @oagen-ignore-file -"""Conformance cases WIF-GCP-01 and WIF-GCP-02, against a local mock server.""" +"""Conformance cases WIF-GCP-01 to WIF-GCP-03, against a local mock server.""" from __future__ import annotations @@ -153,7 +153,7 @@ def test_connection_failure_is_a_provider_error( gcp_metadata(AUDIENCE)() -def test_the_request_does_not_go_through_an_environment_proxy( +def test_WIF_GCP_03_the_request_does_not_go_through_an_environment_proxy( mock: MockServer, monkeypatch: pytest.MonkeyPatch ) -> None: # Nothing listens on the proxy's port: the call works only if it is direct. From 672620f0df1c4d371e2e457f5f1c4c016ea14fe9 Mon Sep 17 00:00:00 2001 From: "Garen J. Torikian" Date: Fri, 13 Nov 2026 13:49:45 -0800 Subject: [PATCH 09/24] fix(workload-identity): Make environment ID optional and align error hints with the server A reading of the server code on 2026-11-13 showed three things the SDK had slightly wrong. The server binds a workload identity client to exactly one environment and takes the environment from that binding, so `x-url-environment-id` selects nothing. `environment_id` is now optional: the header is sent only when an environment ID is set, and an empty string counts as not set. `WORKOS_ENVIRONMENT_ID` still fills the field when it is omitted, and an explicit value still wins. Setting it is a safety check: a value that names a different environment gets `403 environment_mismatch`. The `environment_id` property is now `Optional[str]`. The hints for `invalid_grant`, `invalid_target`, `invalid_client` and `unauthorized_client` are reworded to match what the server returns each code for. The tests use the real scope name, `orgs:write`. WIF-02 gains part (b): credentials with no environment ID send no environment header. The README says that an identity token is good for one exchange, and what that means for `token_file` and `token_env`. Spec: docs/ideation/wif-backend-sdks/shared-design.md (decisions 6, 7 and 8) --- README.md | 11 ++++++-- src/workos/workload_identity.py | 50 +++++++++++++++++++-------------- tests/test_workload_identity.py | 44 ++++++++++++++++++++++++++--- 3 files changed, 77 insertions(+), 28 deletions(-) diff --git a/README.md b/README.md index 05b7b263..dcafb458 100644 --- a/README.md +++ b/README.md @@ -73,7 +73,7 @@ client = WorkOSClient( credentials=WorkloadIdentityCredentials( client_id="client_1234", # the M2M application's client ID token_url="https://.../oauth2/token", # the token exchange endpoint - environment_id="environment_1234", + environment_id="environment_1234", # optional, see below identity_token_provider=github_actions("https://api.workos.com"), ) ) @@ -88,12 +88,14 @@ page = client.organizations.list_organizations() | `identity_token_provider` | | A callable that returns the workload's JWT (required) | | `client_id` | `WORKOS_CLIENT_ID` | The M2M application's client ID (required) | | `token_url` | `WORKOS_WIF_TOKEN_URL` | The token exchange endpoint (required; there is no default) | -| `environment_id` | `WORKOS_ENVIRONMENT_ID` | The environment ID, sent with every API request (required) | +| `environment_id` | `WORKOS_ENVIRONMENT_ID` | The environment ID (optional). When set, it is sent as the `x-url-environment-id` header on every API request | | `resource` | | The resource to request a token for (defaults to `https://api.workos.com`) | | `scope` | `WORKOS_WIF_SCOPE` | The scope to request (omitted when unset) | An explicit argument wins over its environment variable. +`environment_id` is optional. WorkOS binds a workload identity client to exactly one environment, so the header selects nothing, and when no environment ID is set the header is not sent. Setting it is a safety check: if the value names a different environment from the one the client is bound to, the API refuses the request with `403 environment_mismatch`. + ### Platform Providers Each platform's provider is a separate distribution, so the SDK itself gains no dependencies. Install the one you need; installing a provider does not select it. @@ -147,10 +149,13 @@ provider = token_env("MY_IDENTITY_TOKEN") def provider() -> str: return fetch_identity_token_somehow() -# client_id, token_url and environment_id come from the environment here +# client_id and token_url come from the environment here, and so does +# environment_id when WORKOS_ENVIRONMENT_ID is set credentials = WorkloadIdentityCredentials(identity_token_provider=provider) ``` +WorkOS accepts an identity token for one exchange only. The SDK exchanges again about every four minutes. If the file or the variable still holds the same token then, that exchange fails with `invalid_grant`. So use `token_file` and `token_env` for a source that something rewrites before each exchange, or for a job shorter than five minutes. The platform providers (GitHub Actions, GCP and AWS) fetch a new token every time. + With `AsyncWorkOSClient`, a plain function runs in a worker thread so it cannot block the event loop, and an `async def` provider is awaited. ### Workload Identity Errors diff --git a/src/workos/workload_identity.py b/src/workos/workload_identity.py index b08c10d8..f6254846 100644 --- a/src/workos/workload_identity.py +++ b/src/workos/workload_identity.py @@ -63,7 +63,8 @@ # --- constants ------------------------------------------------------------------ -# Sent on every API request made with workload identity credentials. +# Sent on API requests made with workload identity credentials that have an +# environment ID. Left off when they have none. ENVIRONMENT_ID_HEADER = "x-url-environment-id" GRANT_TYPE = "urn:ietf:params:oauth:grant-type:jwt-bearer" DEFAULT_RESOURCE = "https://api.workos.com" @@ -96,22 +97,24 @@ _HINTS: Dict[str, str] = { # OAuth error codes from the token endpoint. "invalid_grant": ( - "The identity token did not match a trust rule for this application, " - "or the token has expired. Check the issuer, audience and subject " - "claims against the trust rule." + "The identity token was not accepted. Check its issuer, audience and " + "subject claims against the trust rule, and that it has not expired. " + "A token that was already exchanged is also refused: each exchange " + "needs a new identity token." ), "invalid_target": ( - "The resource or audience is wrong. The trust rule's audience must " - "match the audience the identity token was requested with, and the " - "resource must be registered for the environment." + "The resource is not one the token endpoint accepts. Leave the " + "resource unset to use the default, https://api.workos.com." ), "invalid_client": ( - "Check that the client ID is the M2M application that has the trust rule." + "The client ID is unknown, or the application has no enabled trust " + "rule. Check that the client ID is the M2M application that has the " + "trust rule." ), "unauthorized_client": ( - "This application is not allowed to use workload identity federation. " - "Check that the feature is enabled for the environment and that the " - "application has a trust rule." + "This application cannot use workload identity federation. Check that " + "the feature is enabled for your team and that the application is " + "bound to a non-production environment." ), "invalid_scope": ( "The requested scope is not allowed for this application. Fix the " @@ -423,8 +426,13 @@ class WorkloadIdentityCredentials: ``WORKOS_CLIENT_ID``. token_url: The token exchange endpoint. Falls back to ``WORKOS_WIF_TOKEN_URL``. There is no built-in default. - environment_id: The environment ID, sent as a header on every API - request. Falls back to ``WORKOS_ENVIRONMENT_ID``. + environment_id: Optional. Falls back to ``WORKOS_ENVIRONMENT_ID``. + When set, it is sent as the ``x-url-environment-id`` header on + every API request; when not set (an empty string counts as not + set), the header is not sent. The server binds a workload + identity client to exactly one environment, so the header + selects nothing. Setting it is a safety check: a value that + names a different environment gets ``403 environment_mismatch``. resource: The ``resource`` to request a token for. Defaults to ``https://api.workos.com``. scope: The ``scope`` to request. Falls back to ``WORKOS_WIF_SCOPE``; @@ -453,8 +461,8 @@ def __init__( self._provider = identity_token_provider self._client_id = self._required("client_id", client_id, _CLIENT_ID_ENV) self._token_url = self._required("token_url", token_url, _TOKEN_URL_ENV) - self._environment_id = self._required( - "environment_id", environment_id, _ENVIRONMENT_ID_ENV + self._environment_id = ( + environment_id or os.environ.get(_ENVIRONMENT_ID_ENV) or None ) self._resource = resource or DEFAULT_RESOURCE self._scope = scope or os.environ.get(_SCOPE_ENV) or None @@ -497,8 +505,8 @@ def token_url(self) -> str: return self._token_url @property - def environment_id(self) -> str: - """The environment ID sent with every API request.""" + def environment_id(self) -> Optional[str]: + """The environment ID sent with every API request, or None when none is sent.""" return self._environment_id @property @@ -565,11 +573,11 @@ def invalidate(self, generation: int) -> None: # --- cache --- def _snapshot(self, token: str, generation: int) -> CredentialSnapshot: + headers = {"Authorization": f"Bearer {token}"} + if self._environment_id: + headers[ENVIRONMENT_ID_HEADER] = self._environment_id return CredentialSnapshot( - headers={ - "Authorization": f"Bearer {token}", - ENVIRONMENT_ID_HEADER: self._environment_id, - }, + headers=headers, generation=generation, recoverable=True, ) diff --git a/tests/test_workload_identity.py b/tests/test_workload_identity.py index 6b31504b..57610ba9 100644 --- a/tests/test_workload_identity.py +++ b/tests/test_workload_identity.py @@ -646,11 +646,11 @@ def WIF_01_first_request_triggers_one_exchange_post(h: Harness) -> None: assert "client_secret" not in post.form # Again on a new instance, with a scope. - h.get(h.client(h.credentials(Provider("assertion-1"), scope="organizations:write"))) + h.get(h.client(h.credentials(Provider("assertion-1"), scope="orgs:write"))) assert h.token.count == 2 scoped = h.token.requests[1] - assert scoped.form["scope"] == "organizations:write" + assert scoped.form["scope"] == "orgs:write" assert "client_secret" not in scoped.form assert "authorization" not in scoped.headers @@ -659,6 +659,7 @@ def WIF_01_first_request_triggers_one_exchange_post(h: Harness) -> None: def WIF_02_api_request_carries_the_access_token_and_environment_header( h: Harness, ) -> None: + # (a) With an environment ID set, the header names it. # No API key and no client ID: the credentials alone are enough to build a client. h.get(h.client(h.credentials())) @@ -668,6 +669,24 @@ def WIF_02_api_request_carries_the_access_token_and_environment_header( assert request.headers["x-url-environment-id"] == "environment_wif_test" +@scenario +def WIF_02_no_environment_id_sends_no_environment_header(h: Harness) -> None: + # (b) No environment ID, explicit or in the environment: the credentials + # are still built, and the header is left off. + h.monkeypatch.delenv("WORKOS_ENVIRONMENT_ID", raising=False) + credentials = h.bare_credentials( + Provider(), client_id=CLIENT_ID, token_url=TOKEN_URL + ) + assert credentials.environment_id is None + + h.get(h.client(credentials)) + + assert h.api.count == 1 + request = h.api.requests[0] + assert request.headers["authorization"] == "Bearer access-1" + assert "x-url-environment-id" not in request.headers + + @scenario def WIF_03_second_request_reuses_the_cached_token(h: Harness) -> None: client = h.client(h.credentials()) @@ -1518,7 +1537,6 @@ def test_one_credentials_instance_serves_both_kinds_of_client( [ ("client_id", "WORKOS_CLIENT_ID"), ("token_url", "WORKOS_WIF_TOKEN_URL"), - ("environment_id", "WORKOS_ENVIRONMENT_ID"), ], ) def test_a_missing_required_setting_fails_at_construction( @@ -1527,7 +1545,6 @@ def test_a_missing_required_setting_fails_at_construction( settings = { "client_id": CLIENT_ID, "token_url": TOKEN_URL, - "environment_id": ENVIRONMENT_ID, } del settings[missing] @@ -1542,6 +1559,25 @@ def test_a_missing_required_setting_fails_at_construction( assert network.token.count == 0 +def test_an_empty_environment_id_counts_as_not_set( + network: Network, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setenv("WORKOS_ENVIRONMENT_ID", "") + credentials = WorkloadIdentityCredentials( + identity_token_provider=Provider(), + client_id=CLIENT_ID, + token_url=TOKEN_URL, + environment_id="", + ) + assert credentials.environment_id is None + + with WorkOSClient(base_url=API_URL, credentials=credentials) as client: + client.request("GET", ("organizations",)) + + assert network.api.bearers() == ["access-1"] + assert "x-url-environment-id" not in network.api.requests[0].headers + + def test_a_provider_that_is_not_callable_fails_at_construction( network: Network, ) -> None: From f0084ee0663a8abb682407acca57fa138715718a Mon Sep 17 00:00:00 2001 From: "Garen J. Torikian" Date: Sat, 14 Nov 2026 11:22:03 -0800 Subject: [PATCH 10/24] fix(workload-identity): Stop reading WORKOS_ENVIRONMENT_ID and correct the README examples The SDK no longer reads `WORKOS_ENVIRONMENT_ID`. `environment_id` is set in code or not at all: left out, `None` or an empty string all mean no `x-url-environment-id` header and no error. The header is an optional safety check, and a variable left in the environment could turn it into a `403 environment_mismatch` with no line of code to point at. The variable did not exist before this work, so removing it breaks no one. `WORKOS_CLIENT_ID`, `WORKOS_WIF_TOKEN_URL` and `WORKOS_WIF_SCOPE` are unchanged. WIF-02 (b) now sets the variable and asserts that no header is sent. WIF-22 no longer sets it or passes an environment ID. The README no longer names the variable. Its `token_file` example describes a file that another process writes, not a Kubernetes token, which the server refuses. It says "a job shorter than four minutes", because the SDK exchanges again at four. Spec: docs/ideation/wif-backend-sdks/shared-design.md (decisions 9 and 10) --- README.md | 12 ++++++------ src/workos/workload_identity.py | 25 ++++++++++++------------- tests/test_workload_identity.py | 19 +++++++------------ 3 files changed, 25 insertions(+), 31 deletions(-) diff --git a/README.md b/README.md index dcafb458..a247ee5d 100644 --- a/README.md +++ b/README.md @@ -88,13 +88,13 @@ page = client.organizations.list_organizations() | `identity_token_provider` | | A callable that returns the workload's JWT (required) | | `client_id` | `WORKOS_CLIENT_ID` | The M2M application's client ID (required) | | `token_url` | `WORKOS_WIF_TOKEN_URL` | The token exchange endpoint (required; there is no default) | -| `environment_id` | `WORKOS_ENVIRONMENT_ID` | The environment ID (optional). When set, it is sent as the `x-url-environment-id` header on every API request | +| `environment_id` | | The environment ID (optional; set in code only). When set, it is sent as the `x-url-environment-id` header on every API request | | `resource` | | The resource to request a token for (defaults to `https://api.workos.com`) | | `scope` | `WORKOS_WIF_SCOPE` | The scope to request (omitted when unset) | An explicit argument wins over its environment variable. -`environment_id` is optional. WorkOS binds a workload identity client to exactly one environment, so the header selects nothing, and when no environment ID is set the header is not sent. Setting it is a safety check: if the value names a different environment from the one the client is bound to, the API refuses the request with `403 environment_mismatch`. +`environment_id` is optional and is set only in code: the SDK reads no environment variable for it. WorkOS binds a workload identity client to exactly one environment, so the header selects nothing, and when no environment ID is set the header is not sent. Setting it is a safety check: if the value names a different environment from the one the client is bound to, the API refuses the request with `403 environment_mismatch`. ### Platform Providers @@ -139,7 +139,8 @@ A provider is any callable that returns the JWT as a string. The SDK ships two, ```python from workos import WorkloadIdentityCredentials, token_env, token_file -# A file, read again on every exchange (for example a projected Kubernetes token) +# A file that another process writes, such as a sidecar or an earlier CI step +# that fetches a new token. The file is read again on every exchange provider = token_file("/var/run/secrets/tokens/workos") # An environment variable, read on every exchange @@ -149,12 +150,11 @@ provider = token_env("MY_IDENTITY_TOKEN") def provider() -> str: return fetch_identity_token_somehow() -# client_id and token_url come from the environment here, and so does -# environment_id when WORKOS_ENVIRONMENT_ID is set +# client_id and token_url come from the environment here credentials = WorkloadIdentityCredentials(identity_token_provider=provider) ``` -WorkOS accepts an identity token for one exchange only. The SDK exchanges again about every four minutes. If the file or the variable still holds the same token then, that exchange fails with `invalid_grant`. So use `token_file` and `token_env` for a source that something rewrites before each exchange, or for a job shorter than five minutes. The platform providers (GitHub Actions, GCP and AWS) fetch a new token every time. +WorkOS accepts an identity token for one exchange only. The SDK exchanges again about every four minutes. If the file or the variable still holds the same token then, that exchange fails with `invalid_grant`. So use `token_file` and `token_env` for a source that something rewrites before each exchange, or for a job shorter than four minutes. The platform providers (GitHub Actions, GCP and AWS) fetch a new token every time. With `AsyncWorkOSClient`, a plain function runs in a worker thread so it cannot block the event loop, and an `async def` provider is awaited. diff --git a/src/workos/workload_identity.py b/src/workos/workload_identity.py index f6254846..d00af1b8 100644 --- a/src/workos/workload_identity.py +++ b/src/workos/workload_identity.py @@ -80,7 +80,6 @@ _CLIENT_ID_ENV = "WORKOS_CLIENT_ID" _TOKEN_URL_ENV = "WORKOS_WIF_TOKEN_URL" _SCOPE_ENV = "WORKOS_WIF_SCOPE" -_ENVIRONMENT_ID_ENV = "WORKOS_ENVIRONMENT_ID" # How long past its deadline a synchronous exchange may run before a waiter # gives it up for lost. See WorkloadIdentityCredentials._wait. @@ -415,8 +414,9 @@ class WorkloadIdentityCredentials: even with identical settings. Settings are fixed at construction; build a new instance to change one. An - omitted setting falls back to its environment variable. The environment - variables never switch workload identity on by themselves. + omitted ``client_id``, ``token_url`` or ``scope`` falls back to its + environment variable. The environment variables never switch workload + identity on by themselves. Args: identity_token_provider: A callable returning the workload's JWT, such @@ -426,13 +426,14 @@ class WorkloadIdentityCredentials: ``WORKOS_CLIENT_ID``. token_url: The token exchange endpoint. Falls back to ``WORKOS_WIF_TOKEN_URL``. There is no built-in default. - environment_id: Optional. Falls back to ``WORKOS_ENVIRONMENT_ID``. - When set, it is sent as the ``x-url-environment-id`` header on - every API request; when not set (an empty string counts as not - set), the header is not sent. The server binds a workload - identity client to exactly one environment, so the header - selects nothing. Setting it is a safety check: a value that - names a different environment gets ``403 environment_mismatch``. + environment_id: Optional, and set only here: no environment variable + is read for it. When set, it is sent as the + ``x-url-environment-id`` header on every API request; when not + set (an empty string counts as not set), the header is not sent. + The server binds a workload identity client to exactly one + environment, so the header selects nothing. Setting it is a + safety check: a value that names a different environment gets + ``403 environment_mismatch``. resource: The ``resource`` to request a token for. Defaults to ``https://api.workos.com``. scope: The ``scope`` to request. Falls back to ``WORKOS_WIF_SCOPE``; @@ -461,9 +462,7 @@ def __init__( self._provider = identity_token_provider self._client_id = self._required("client_id", client_id, _CLIENT_ID_ENV) self._token_url = self._required("token_url", token_url, _TOKEN_URL_ENV) - self._environment_id = ( - environment_id or os.environ.get(_ENVIRONMENT_ID_ENV) or None - ) + self._environment_id = environment_id or None self._resource = resource or DEFAULT_RESOURCE self._scope = scope or os.environ.get(_SCOPE_ENV) or None diff --git a/tests/test_workload_identity.py b/tests/test_workload_identity.py index 57610ba9..037d50b3 100644 --- a/tests/test_workload_identity.py +++ b/tests/test_workload_identity.py @@ -57,7 +57,6 @@ "WORKOS_CLIENT_ID", "WORKOS_WIF_TOKEN_URL", "WORKOS_WIF_SCOPE", - "WORKOS_ENVIRONMENT_ID", "WORKOS_BASE_URL", ) OAUTH_CODES = ( @@ -671,9 +670,10 @@ def WIF_02_api_request_carries_the_access_token_and_environment_header( @scenario def WIF_02_no_environment_id_sends_no_environment_header(h: Harness) -> None: - # (b) No environment ID, explicit or in the environment: the credentials - # are still built, and the header is left off. - h.monkeypatch.delenv("WORKOS_ENVIRONMENT_ID", raising=False) + # (b) No environment ID in code: the credentials are still built, and the + # header is left off. The variable is set to show that the SDK does not + # read it. + h.monkeypatch.setenv("WORKOS_ENVIRONMENT_ID", "environment_env") credentials = h.bare_credentials( Provider(), client_id=CLIENT_ID, token_url=TOKEN_URL ) @@ -1104,14 +1104,12 @@ def WIF_22_env_and_callback_providers_and_environment_defaults(h: Harness) -> No h.monkeypatch.setenv("WORKOS_CLIENT_ID", "client_env") h.monkeypatch.setenv("WORKOS_WIF_TOKEN_URL", TOKEN_URL) h.monkeypatch.setenv("WORKOS_WIF_SCOPE", "scope_env") - h.monkeypatch.setenv("WORKOS_ENVIRONMENT_ID", "environment_env") before = h.token.count h.get(h.client(h.bare_credentials(Provider()))) assert h.token.count == before + 1 assert h.token.requests[-1].url == TOKEN_URL assert h.token.forms()[-1]["client_id"] == "client_env" assert h.token.forms()[-1]["scope"] == "scope_env" - assert h.api.requests[-1].headers["x-url-environment-id"] == "environment_env" # (d) Explicit values win over the environment. h.get( @@ -1120,13 +1118,11 @@ def WIF_22_env_and_callback_providers_and_environment_defaults(h: Harness) -> No Provider(), client_id="client_explicit", scope="scope_explicit", - environment_id="environment_explicit", ) ) ) assert h.token.forms()[-1]["client_id"] == "client_explicit" assert h.token.forms()[-1]["scope"] == "scope_explicit" - assert h.api.requests[-1].headers["x-url-environment-id"] == "environment_explicit" @scenario @@ -1559,15 +1555,15 @@ def test_a_missing_required_setting_fails_at_construction( assert network.token.count == 0 +@pytest.mark.parametrize("environment_id", ["", None]) def test_an_empty_environment_id_counts_as_not_set( - network: Network, monkeypatch: pytest.MonkeyPatch + network: Network, environment_id: Optional[str] ) -> None: - monkeypatch.setenv("WORKOS_ENVIRONMENT_ID", "") credentials = WorkloadIdentityCredentials( identity_token_provider=Provider(), client_id=CLIENT_ID, token_url=TOKEN_URL, - environment_id="", + environment_id=environment_id, ) assert credentials.environment_id is None @@ -1615,7 +1611,6 @@ def test_the_environment_alone_never_turns_workload_identity_on( ) -> None: monkeypatch.setenv("WORKOS_CLIENT_ID", "client_env") monkeypatch.setenv("WORKOS_WIF_TOKEN_URL", TOKEN_URL) - monkeypatch.setenv("WORKOS_ENVIRONMENT_ID", "environment_env") monkeypatch.setenv("WORKOS_API_KEY", "sk_test_env") with WorkOSClient(base_url=API_URL) as client: From e0e14c79efd440d2e97ed7d4cff968accf427f9b Mon Sep 17 00:00:00 2001 From: "Garen J. Torikian" Date: Sat, 14 Nov 2026 11:29:28 -0800 Subject: [PATCH 11/24] fix(workload-identity): Stop reading WORKOS_WIF_TOKEN_URL and WORKOS_WIF_SCOPE `token_url` and `scope` are now set in code only. `WORKOS_CLIENT_ID` is the only environment variable the credentials read. `token_url` is still required: missing or empty is an error at construction, with the description `token_url is required`. `scope` is still optional: not set, `None` or empty means no `scope` field in the exchange request. Both variable names came from the CLI spike, where variables are the only way to configure a command. With no scope a token carries every scope the application holds, so a variable left in the environment would change permissions with no line of code to point at. Neither variable has been released, so removing them breaks no one. WIF-22 now sets both variables to show that they are ignored, and gains part (e): with no token URL in code, the credentials cannot be built. The README no longer names the two variables, and its example that relied on them passes the token URL in code. The example token file path is now `/run/workos/identity-token`, shared by all nine SDKs; the old path was a Kubernetes one. Spec: docs/ideation/wif-backend-sdks/shared-design.md (decision 11) --- README.md | 17 +++++---- src/workos/workload_identity.py | 40 +++++++++++--------- tests/test_workload_identity.py | 67 +++++++++++++++++++++------------ 3 files changed, 74 insertions(+), 50 deletions(-) diff --git a/README.md b/README.md index a247ee5d..062574e5 100644 --- a/README.md +++ b/README.md @@ -87,14 +87,14 @@ page = client.organizations.list_organizations() |----------|----------------------|-------------| | `identity_token_provider` | | A callable that returns the workload's JWT (required) | | `client_id` | `WORKOS_CLIENT_ID` | The M2M application's client ID (required) | -| `token_url` | `WORKOS_WIF_TOKEN_URL` | The token exchange endpoint (required; there is no default) | +| `token_url` | | The token exchange endpoint (required; set in code only, and there is no default) | | `environment_id` | | The environment ID (optional; set in code only). When set, it is sent as the `x-url-environment-id` header on every API request | | `resource` | | The resource to request a token for (defaults to `https://api.workos.com`) | -| `scope` | `WORKOS_WIF_SCOPE` | The scope to request (omitted when unset) | +| `scope` | | The scope to request (optional; set in code only, and omitted when unset) | -An explicit argument wins over its environment variable. +`WORKOS_CLIENT_ID` is the only environment variable the credentials read, and an explicit `client_id` wins over it. Every other argument is set in code. -`environment_id` is optional and is set only in code: the SDK reads no environment variable for it. WorkOS binds a workload identity client to exactly one environment, so the header selects nothing, and when no environment ID is set the header is not sent. Setting it is a safety check: if the value names a different environment from the one the client is bound to, the API refuses the request with `403 environment_mismatch`. +`environment_id` is optional. WorkOS binds a workload identity client to exactly one environment, so the header selects nothing, and when no environment ID is set the header is not sent. Setting it is a safety check: if the value names a different environment from the one the client is bound to, the API refuses the request with `403 environment_mismatch`. ### Platform Providers @@ -141,7 +141,7 @@ from workos import WorkloadIdentityCredentials, token_env, token_file # A file that another process writes, such as a sidecar or an earlier CI step # that fetches a new token. The file is read again on every exchange -provider = token_file("/var/run/secrets/tokens/workos") +provider = token_file("/run/workos/identity-token") # An environment variable, read on every exchange provider = token_env("MY_IDENTITY_TOKEN") @@ -150,8 +150,11 @@ provider = token_env("MY_IDENTITY_TOKEN") def provider() -> str: return fetch_identity_token_somehow() -# client_id and token_url come from the environment here -credentials = WorkloadIdentityCredentials(identity_token_provider=provider) +# client_id comes from WORKOS_CLIENT_ID here +credentials = WorkloadIdentityCredentials( + token_url="https://.../oauth2/token", + identity_token_provider=provider, +) ``` WorkOS accepts an identity token for one exchange only. The SDK exchanges again about every four minutes. If the file or the variable still holds the same token then, that exchange fails with `invalid_grant`. So use `token_file` and `token_env` for a source that something rewrites before each exchange, or for a job shorter than four minutes. The platform providers (GitHub Actions, GCP and AWS) fetch a new token every time. diff --git a/src/workos/workload_identity.py b/src/workos/workload_identity.py index d00af1b8..21815281 100644 --- a/src/workos/workload_identity.py +++ b/src/workos/workload_identity.py @@ -15,7 +15,7 @@ client_id="client_...", token_url="https://.../oauth2/token", environment_id="environment_...", - identity_token_provider=token_file("/var/run/secrets/tokens/workos"), + identity_token_provider=token_file("/run/workos/identity-token"), ) ) @@ -77,9 +77,8 @@ EXCHANGE_DEADLINE_SECONDS = 30.0 DESCRIPTION_LIMIT = 500 +# The only environment variable the credentials read. _CLIENT_ID_ENV = "WORKOS_CLIENT_ID" -_TOKEN_URL_ENV = "WORKOS_WIF_TOKEN_URL" -_SCOPE_ENV = "WORKOS_WIF_SCOPE" # How long past its deadline a synchronous exchange may run before a waiter # gives it up for lost. See WorkloadIdentityCredentials._wait. @@ -414,9 +413,9 @@ class WorkloadIdentityCredentials: even with identical settings. Settings are fixed at construction; build a new instance to change one. An - omitted ``client_id``, ``token_url`` or ``scope`` falls back to its - environment variable. The environment variables never switch workload - identity on by themselves. + omitted ``client_id`` falls back to ``WORKOS_CLIENT_ID``, the only + environment variable the credentials read. No environment variable + switches workload identity on. Args: identity_token_provider: A callable returning the workload's JWT, such @@ -424,8 +423,9 @@ class WorkloadIdentityCredentials: your own function. client_id: The M2M application's client ID. Falls back to ``WORKOS_CLIENT_ID``. - token_url: The token exchange endpoint. Falls back to - ``WORKOS_WIF_TOKEN_URL``. There is no built-in default. + token_url: The token exchange endpoint. Required, and set only here: + no environment variable is read for it and there is no built-in + default. environment_id: Optional, and set only here: no environment variable is read for it. When set, it is sent as the ``x-url-environment-id`` header on every API request; when not @@ -436,12 +436,14 @@ class WorkloadIdentityCredentials: ``403 environment_mismatch``. resource: The ``resource`` to request a token for. Defaults to ``https://api.workos.com``. - scope: The ``scope`` to request. Falls back to ``WORKOS_WIF_SCOPE``; - left out of the request when empty. + scope: The ``scope`` to request. Optional, and set only here: no + environment variable is read for it. Left out of the request when + not set or empty. Raises: WorkloadIdentityError: With code ``invalid_configuration`` when a - required setting is missing after the environment is consulted. + required setting is missing; for ``client_id``, that is after + ``WORKOS_CLIENT_ID`` is consulted. """ def __init__( @@ -461,10 +463,10 @@ def __init__( ) self._provider = identity_token_provider self._client_id = self._required("client_id", client_id, _CLIENT_ID_ENV) - self._token_url = self._required("token_url", token_url, _TOKEN_URL_ENV) + self._token_url = self._required("token_url", token_url) self._environment_id = environment_id or None self._resource = resource or DEFAULT_RESOURCE - self._scope = scope or os.environ.get(_SCOPE_ENV) or None + self._scope = scope or None # The cache. Guarded by _lock, which is held only for these few fields # and never across I/O, so both the sync and the async path may take it. @@ -485,12 +487,14 @@ def __init__( self._async_sleep: Callable[[float], Awaitable[None]] = asyncio.sleep @staticmethod - def _required(field: str, value: Optional[str], env: str) -> str: - resolved = value or os.environ.get(env) + def _required(field: str, value: Optional[str], env: Optional[str] = None) -> str: + """A required setting, from the argument or, when it has one, ``env``.""" + resolved = value or (os.environ.get(env) if env else None) if not resolved: - raise WorkloadIdentityError( - "invalid_configuration", f"{field} is required (or set {env})" - ) + description = f"{field} is required" + if env: + description = f"{description} (or set {env})" + raise WorkloadIdentityError("invalid_configuration", description) return resolved @property diff --git a/tests/test_workload_identity.py b/tests/test_workload_identity.py index 037d50b3..7cd7c075 100644 --- a/tests/test_workload_identity.py +++ b/tests/test_workload_identity.py @@ -51,12 +51,12 @@ TOKEN_URL = "https://token.test/oauth2/token" API_URL = "https://api.test" ELSEWHERE_URL = "https://elsewhere.test/oauth2/token" +# No mock answers this host: a request to it fails the test. +IGNORED_URL = "https://ignored.example.test/oauth2/token" ENVIRONMENT = ( "WORKOS_API_KEY", "WORKOS_CLIENT_ID", - "WORKOS_WIF_TOKEN_URL", - "WORKOS_WIF_SCOPE", "WORKOS_BASE_URL", ) OAUTH_CODES = ( @@ -1052,13 +1052,13 @@ def WIF_20_explicit_credentials_win_over_the_environment_api_key(h: Harness) -> assert h.api.bearers() == ["access-1"] assert client._api_key is None - # (b) Credentials with no token URL, explicit or in the environment, cannot be built. + # (b) Credentials with no token URL cannot be built. with pytest.raises(WorkloadIdentityError) as missing: h.bare_credentials( Provider(), client_id=CLIENT_ID, environment_id=ENVIRONMENT_ID ) assert missing.value.code == "invalid_configuration" - assert "token_url is required (or set WORKOS_WIF_TOKEN_URL)" in str(missing.value) + assert missing.value.description == "token_url is required" # (c) A failing exchange is an error, never a fall back to the key. h.token.script.append(oauth_error("invalid_client")) @@ -1100,29 +1100,34 @@ def WIF_22_env_and_callback_providers_and_environment_defaults(h: Harness) -> No h.get(h.client(h.credentials(lambda: "assertion-cb"))) assert h.token.forms()[-1]["assertion"] == "assertion-cb" - # (c) Omitted settings default from the environment. + # (c) Only client_id defaults from the environment. The token URL and + # scope variables are set to show that the SDK does not read them. h.monkeypatch.setenv("WORKOS_CLIENT_ID", "client_env") - h.monkeypatch.setenv("WORKOS_WIF_TOKEN_URL", TOKEN_URL) + h.monkeypatch.setenv("WORKOS_WIF_TOKEN_URL", IGNORED_URL) h.monkeypatch.setenv("WORKOS_WIF_SCOPE", "scope_env") before = h.token.count - h.get(h.client(h.bare_credentials(Provider()))) + h.get(h.client(h.bare_credentials(Provider(), token_url=TOKEN_URL))) assert h.token.count == before + 1 assert h.token.requests[-1].url == TOKEN_URL assert h.token.forms()[-1]["client_id"] == "client_env" - assert h.token.forms()[-1]["scope"] == "scope_env" + assert "scope" not in h.token.forms()[-1] - # (d) Explicit values win over the environment. + # (d) An explicit client_id wins over the environment. h.get( h.client( h.bare_credentials( - Provider(), - client_id="client_explicit", - scope="scope_explicit", + Provider(), client_id="client_explicit", token_url=TOKEN_URL ) ) ) assert h.token.forms()[-1]["client_id"] == "client_explicit" - assert h.token.forms()[-1]["scope"] == "scope_explicit" + + # (e) With no token URL in code, the credentials cannot be built. + with pytest.raises(WorkloadIdentityError) as missing: + h.bare_credentials(Provider()) + assert missing.value.code == "invalid_configuration" + assert missing.value.description == "token_url is required" + assert h.token.count == before + 2 @scenario @@ -1529,26 +1534,21 @@ def test_one_credentials_instance_serves_both_kinds_of_client( @pytest.mark.parametrize( - ("missing", "variable"), + ("settings", "description"), [ - ("client_id", "WORKOS_CLIENT_ID"), - ("token_url", "WORKOS_WIF_TOKEN_URL"), + ({"token_url": TOKEN_URL}, "client_id is required (or set WORKOS_CLIENT_ID)"), + ({"client_id": CLIENT_ID}, "token_url is required"), + ({"client_id": CLIENT_ID, "token_url": ""}, "token_url is required"), ], ) def test_a_missing_required_setting_fails_at_construction( - network: Network, missing: str, variable: str + network: Network, settings: Dict[str, str], description: str ) -> None: - settings = { - "client_id": CLIENT_ID, - "token_url": TOKEN_URL, - } - del settings[missing] - with pytest.raises(WorkloadIdentityError) as caught: WorkloadIdentityCredentials(identity_token_provider=Provider(), **settings) assert caught.value.code == "invalid_configuration" - assert caught.value.description == f"{missing} is required (or set {variable})" + assert caught.value.description == description assert caught.value.hint == ( "Workload identity credentials are missing a required setting." ) @@ -1574,6 +1574,24 @@ def test_an_empty_environment_id_counts_as_not_set( assert "x-url-environment-id" not in network.api.requests[0].headers +@pytest.mark.parametrize("scope", ["", None]) +def test_an_empty_scope_counts_as_not_set( + network: Network, scope: Optional[str] +) -> None: + credentials = WorkloadIdentityCredentials( + identity_token_provider=Provider(), + client_id=CLIENT_ID, + token_url=TOKEN_URL, + scope=scope, + ) + assert credentials.scope is None + + with WorkOSClient(base_url=API_URL, credentials=credentials) as client: + client.request("GET", ("organizations",)) + + assert "scope" not in network.token.forms()[0] + + def test_a_provider_that_is_not_callable_fails_at_construction( network: Network, ) -> None: @@ -1610,7 +1628,6 @@ def test_the_environment_alone_never_turns_workload_identity_on( network: Network, monkeypatch: pytest.MonkeyPatch ) -> None: monkeypatch.setenv("WORKOS_CLIENT_ID", "client_env") - monkeypatch.setenv("WORKOS_WIF_TOKEN_URL", TOKEN_URL) monkeypatch.setenv("WORKOS_API_KEY", "sk_test_env") with WorkOSClient(base_url=API_URL) as client: From ba6f1c44eeac7e67dc254132a973464791da680e Mon Sep 17 00:00:00 2001 From: "Garen J. Torikian" Date: Mon, 16 Nov 2026 15:11:19 -0500 Subject: [PATCH 12/24] fix(workload-identity): Require an https token URL `WorkloadIdentityCredentials` now refuses a `token_url` that is not an absolute `https` URL. The exchange POST carries the workload's identity token and the response carries the access token, so neither may travel over plain HTTP. workos-php already has this rule. The check runs at construction, after the existing `token_url is required` check. A URL with another scheme, no scheme or no host raises `WorkloadIdentityError` with the code `invalid_configuration` and the description `token_url must be an absolute https URL`. The scheme is not case-sensitive, so `HTTPS://` is accepted. `http://localhost` and loopback addresses are refused like any other host. No argument and no environment variable relaxes the rule. The URL is parsed with httpx2, the client that sends the exchange, and not with `urllib.parse`. The two read some input differently: `urlsplit` drops leading whitespace and does not check the port, so it would pass URLs that httpx2 cannot send. Such a URL is now refused at construction too. The error leaves the URL out, because a URL can hold credentials. One class serves both `WorkOSClient` and `AsyncWorkOSClient`, so one helper, `_https_url`, covers both. The existing tests already use `https` token URLs against a mocked transport, so none needed a change and there is no test-only switch. The provider packages never build credentials and are unchanged. The README and the docstrings say that the token URL must be `https`. --- README.md | 4 ++- src/workos/workload_identity.py | 37 +++++++++++++++++--- tests/test_workload_identity.py | 60 +++++++++++++++++++++++++++++++++ 3 files changed, 96 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 062574e5..053c5d73 100644 --- a/README.md +++ b/README.md @@ -87,13 +87,15 @@ page = client.organizations.list_organizations() |----------|----------------------|-------------| | `identity_token_provider` | | A callable that returns the workload's JWT (required) | | `client_id` | `WORKOS_CLIENT_ID` | The M2M application's client ID (required) | -| `token_url` | | The token exchange endpoint (required; set in code only, and there is no default) | +| `token_url` | | The token exchange endpoint (required; set in code only, and there is no default). It must be an `https` URL | | `environment_id` | | The environment ID (optional; set in code only). When set, it is sent as the `x-url-environment-id` header on every API request | | `resource` | | The resource to request a token for (defaults to `https://api.workos.com`) | | `scope` | | The scope to request (optional; set in code only, and omitted when unset) | `WORKOS_CLIENT_ID` is the only environment variable the credentials read, and an explicit `client_id` wins over it. Every other argument is set in code. +`token_url` must be an absolute `https` URL, because the exchange request carries the workload's identity token and the response carries the access token. Any other URL, `http://localhost` included, raises `WorkloadIdentityError` with the code `invalid_configuration` when the credentials are built. + `environment_id` is optional. WorkOS binds a workload identity client to exactly one environment, so the header selects nothing, and when no environment ID is set the header is not sent. Setting it is a safety check: if the value names a different environment from the one the client is bound to, the API refuses the request with `403 environment_mismatch`. ### Platform Providers diff --git a/src/workos/workload_identity.py b/src/workos/workload_identity.py index 21815281..4c645a8f 100644 --- a/src/workos/workload_identity.py +++ b/src/workos/workload_identity.py @@ -22,6 +22,9 @@ The identity token provider is any callable that returns the workload's JWT. :func:`token_file` and :func:`token_env` are built in; the GitHub Actions, GCP and AWS providers are separate distributions. + +The token URL must be an absolute ``https`` URL. Any other URL fails when the +credentials are built. """ from __future__ import annotations @@ -404,6 +407,28 @@ def _retrieve_exception(task: "asyncio.Task[Tuple[str, int]]") -> None: # --- credentials ---------------------------------------------------------------- +def _https_url(token_url: str) -> str: + """``token_url`` unchanged, if it is an absolute https URL. Raises when it is not. + + https only, on every host: the POST carries the workload's identity token + and the response carries the access token. Nothing relaxes this, for + localhost or a loopback address either. + + The URL is parsed by httpx2, which also sends the exchange, so the check + and the request read it the same way. + """ + try: + url = httpx2.URL(token_url) + except (TypeError, httpx2.InvalidURL): + url = None + if url is None or url.scheme != "https" or not url.host: + # The URL itself is left out of the error: it may hold credentials. + raise WorkloadIdentityError( + "invalid_configuration", "token_url must be an absolute https URL" + ) + return token_url + + class WorkloadIdentityCredentials: """Credentials that exchange a workload's JWT for a WorkOS access token. @@ -425,7 +450,10 @@ class WorkloadIdentityCredentials: ``WORKOS_CLIENT_ID``. token_url: The token exchange endpoint. Required, and set only here: no environment variable is read for it and there is no built-in - default. + default. It must be an absolute ``https`` URL. The scheme is not + case-sensitive. Any other URL is refused, ``http://localhost`` + included, because the request carries the identity token and the + response carries the access token. environment_id: Optional, and set only here: no environment variable is read for it. When set, it is sent as the ``x-url-environment-id`` header on every API request; when not @@ -443,7 +471,8 @@ class WorkloadIdentityCredentials: Raises: WorkloadIdentityError: With code ``invalid_configuration`` when a required setting is missing; for ``client_id``, that is after - ``WORKOS_CLIENT_ID`` is consulted. + ``WORKOS_CLIENT_ID`` is consulted. The same code is raised when + ``token_url`` is not an absolute ``https`` URL. """ def __init__( @@ -463,7 +492,7 @@ def __init__( ) self._provider = identity_token_provider self._client_id = self._required("client_id", client_id, _CLIENT_ID_ENV) - self._token_url = self._required("token_url", token_url) + self._token_url = _https_url(self._required("token_url", token_url)) self._environment_id = environment_id or None self._resource = resource or DEFAULT_RESOURCE self._scope = scope or None @@ -504,7 +533,7 @@ def client_id(self) -> str: @property def token_url(self) -> str: - """The token exchange endpoint.""" + """The token exchange endpoint, an absolute ``https`` URL.""" return self._token_url @property diff --git a/tests/test_workload_identity.py b/tests/test_workload_identity.py index 7cd7c075..4cc55364 100644 --- a/tests/test_workload_identity.py +++ b/tests/test_workload_identity.py @@ -1555,6 +1555,66 @@ def test_a_missing_required_setting_fails_at_construction( assert network.token.count == 0 +@pytest.mark.parametrize( + "token_url", + [ + "http://example.com/oauth2/token", + # Loopback hosts are no exception. + "http://localhost:8080/oauth2/token", + "http://127.0.0.1/oauth2/token", + "http://[::1]/oauth2/token", + # No host. + "https:///oauth2/token", + "https://:8443/oauth2/token", + "https:token.test/oauth2/token", + # No scheme. + "token.test/oauth2/token", + "//token.test/oauth2/token", + "/oauth2/token", + # Another scheme. + "ftp://token.test/oauth2/token", + # Not a URL the HTTP client can read. + " https://token.test/oauth2/token", + "\thttps://token.test/oauth2/token", + "https://token.test:port/oauth2/token", + ], +) +def test_a_token_url_that_is_not_absolute_https_fails_at_construction( + network: Network, token_url: str +) -> None: + with pytest.raises(WorkloadIdentityError) as caught: + WorkloadIdentityCredentials( + identity_token_provider=Provider(), + client_id=CLIENT_ID, + token_url=token_url, + ) + + assert caught.value.code == "invalid_configuration" + assert caught.value.description == "token_url must be an absolute https URL" + assert str(caught.value) == ( + "invalid_configuration: Workload identity credentials are missing a " + "required setting. token_url must be an absolute https URL" + ) + assert caught.value.__cause__ is None + assert network.token.count == 0 + + +def test_the_token_url_scheme_is_not_case_sensitive(network: Network) -> None: + token_url = "HTTPS://token.test/oauth2/token" + credentials = WorkloadIdentityCredentials( + identity_token_provider=Provider(), + client_id=CLIENT_ID, + token_url=token_url, + ) + assert credentials.token_url == token_url + + with WorkOSClient(base_url=API_URL, credentials=credentials) as client: + client.request("GET", ("organizations",)) + + assert network.token.requests[0].url == TOKEN_URL + assert network.api.bearers() == ["access-1"] + + @pytest.mark.parametrize("environment_id", ["", None]) def test_an_empty_environment_id_counts_as_not_set( network: Network, environment_id: Optional[str] From 86910ff0fe8b40f312f26ac099b4edec43c34492 Mon Sep 17 00:00:00 2001 From: "Garen J. Torikian" Date: Fri, 20 Nov 2026 16:48:38 -0500 Subject: [PATCH 13/24] fix(workload-identity): Say why the GCP metadata server could not be reached When the GCP provider got no HTTP response from the metadata server, its error named only the exception class: `GCP metadata identity request failed: URLError.` That does not say whether the name failed to resolve, the connection was refused or the request timed out, and it does not say that the provider works only on Google Cloud. The description is now this, on one line: The GCP metadata server could not be reached: . This provider works only on Google Cloud (Compute Engine, GKE, Cloud Run, Cloud Functions). `` is the cause in its own words, for example `[Errno -2] Name or service not known`, `[Errno 111] Connection refused` or `timed out`. For a `URLError` it is the error's `reason`. A timeout while waiting for the response arrives unwrapped and is read the same way. A cause with no text becomes `timed out` for a timeout and `unknown network error` otherwise, so the reason is never empty and never a class name. Nothing else changes. The provider still raises `GcpMetadataProviderError`, which the SDK reports as `provider_failed` and retries. The request, the 10-second timeout and the rule that the request never goes through a proxy are the same. The error for a non-200 status, which already names the status, and the error for an empty body are unchanged. The tests cover a name that does not resolve, a refused connection and a timeout, and each one checks the whole description. --- .../workos_workload_identity_gcp/__init__.py | 21 ++++- .../tests/test_gcp_metadata.py | 79 ++++++++++++++++++- 2 files changed, 96 insertions(+), 4 deletions(-) diff --git a/packages/workos-workload-identity-gcp/src/workos_workload_identity_gcp/__init__.py b/packages/workos-workload-identity-gcp/src/workos_workload_identity_gcp/__init__.py index b0f6e036..f5849f7c 100644 --- a/packages/workos-workload-identity-gcp/src/workos_workload_identity_gcp/__init__.py +++ b/packages/workos-workload-identity-gcp/src/workos_workload_identity_gcp/__init__.py @@ -32,6 +32,23 @@ class GcpMetadataProviderError(Exception): """The GCP metadata server did not return an identity token.""" +def _unreachable(exc: OSError) -> GcpMetadataProviderError: + """The error for a request that got no HTTP response, with the cause in words.""" + # urllib wraps a failed connection in ``URLError`` and keeps the cause in + # ``reason``. A timeout while waiting for the response arrives unwrapped. + cause: object = exc.reason if isinstance(exc, urllib.error.URLError) else exc + reason = str(cause).strip() + if not reason: + reason = ( + "timed out" if isinstance(cause, TimeoutError) else "unknown network error" + ) + return GcpMetadataProviderError( + f"The GCP metadata server could not be reached: {reason}. " + "This provider works only on Google Cloud " + "(Compute Engine, GKE, Cloud Run, Cloud Functions)." + ) + + class _NoRedirect(urllib.request.HTTPRedirectHandler): """Turns every redirect into an ``HTTPError`` instead of following it.""" @@ -76,9 +93,7 @@ def provider() -> str: f"GCP metadata identity request failed with status {exc.code}." ) from None except OSError as exc: - raise GcpMetadataProviderError( - f"GCP metadata identity request failed: {type(exc).__name__}." - ) from None + raise _unreachable(exc) from None if status != 200: raise GcpMetadataProviderError( f"GCP metadata identity request failed with status {status}." diff --git a/packages/workos-workload-identity-gcp/tests/test_gcp_metadata.py b/packages/workos-workload-identity-gcp/tests/test_gcp_metadata.py index 815afa25..c6491388 100644 --- a/packages/workos-workload-identity-gcp/tests/test_gcp_metadata.py +++ b/packages/workos-workload-identity-gcp/tests/test_gcp_metadata.py @@ -4,7 +4,10 @@ from __future__ import annotations +import errno import http.server +import os +import socket import threading from dataclasses import dataclass, field from typing import Dict, Iterator, List @@ -18,6 +21,15 @@ IDENTITY_PATH = "/computeMetadata/v1/instance/service-accounts/default/identity" +def unreachable(reason: str) -> str: + """The whole error text for a request that got no HTTP response.""" + return ( + f"The GCP metadata server could not be reached: {reason}. " + "This provider works only on Google Cloud " + "(Compute Engine, GKE, Cloud Run, Cloud Functions)." + ) + + @dataclass class Recorded: method: str @@ -149,9 +161,74 @@ def test_connection_failure_is_a_provider_error( server.close() monkeypatch.setattr(gcp, "_METADATA_BASE_URL", unused) - with pytest.raises(GcpMetadataProviderError): + with pytest.raises(GcpMetadataProviderError) as raised: + gcp_metadata(AUDIENCE)() + + # The number differs by platform: 111 on Linux, 61 on macOS. + refused = f"[Errno {errno.ECONNREFUSED}] {os.strerror(errno.ECONNREFUSED)}" + assert refused.endswith("Connection refused") + assert str(raised.value) == unreachable(refused) + + +def test_name_resolution_failure_names_the_reason( + monkeypatch: pytest.MonkeyPatch, +) -> None: + asked: List[object] = [] + + def no_such_name(host: object, *args: object, **kwargs: object) -> None: + asked.append(host) + raise socket.gaierror(-2, "Name or service not known") + + monkeypatch.setattr(socket, "getaddrinfo", no_such_name) + + with pytest.raises(GcpMetadataProviderError) as raised: gcp_metadata(AUDIENCE)() + assert str(raised.value) == unreachable("[Errno -2] Name or service not known") + assert asked == ["metadata.google.internal"] + + +def test_timeout_waiting_for_the_response_names_the_reason( + monkeypatch: pytest.MonkeyPatch, +) -> None: + # A listener that never accepts: the connection opens through its backlog + # and no response ever comes. + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as silent: + silent.bind(("127.0.0.1", 0)) + silent.listen(1) + monkeypatch.setattr( + gcp, "_METADATA_BASE_URL", f"http://127.0.0.1:{silent.getsockname()[1]}" + ) + monkeypatch.setattr(gcp, "_TIMEOUT_SECONDS", 0.2) + + with pytest.raises(GcpMetadataProviderError) as raised: + gcp_metadata(AUDIENCE)() + + assert str(raised.value) == unreachable("timed out") + + +@pytest.mark.parametrize( + ("failure", "reason"), + [ + (TimeoutError("timed out"), "timed out"), + (TimeoutError(), "timed out"), + (OSError(), "unknown network error"), + ], + ids=["timeout", "timeout without text", "other failure without text"], +) +def test_connect_failure_always_names_a_reason( + monkeypatch: pytest.MonkeyPatch, failure: OSError, reason: str +) -> None: + def fail(*args: object, **kwargs: object) -> None: + raise failure + + monkeypatch.setattr(socket, "create_connection", fail) + + with pytest.raises(GcpMetadataProviderError) as raised: + gcp_metadata(AUDIENCE)() + + assert str(raised.value) == unreachable(reason) + def test_WIF_GCP_03_the_request_does_not_go_through_an_environment_proxy( mock: MockServer, monkeypatch: pytest.MonkeyPatch From 6ae85b7492adc0989c70a565dd132e0f4f8d0cb8 Mon Sep 17 00:00:00 2001 From: "Garen J. Torikian" Date: Sun, 22 Nov 2026 23:27:07 -0500 Subject: [PATCH 14/24] fix(workload-identity): Say why an endpoint could not be reached When a request got no HTTP response, three errors named only an exception class: The request to the token endpoint failed (TransportConnectError). GitHub Actions OIDC token request failed: URLError. sts:GetWebIdentityToken failed with EndpointConnectionError. None of them says whether the name failed to resolve, the connection was refused, the request timed out or the TLS handshake failed, and none names the host that was tried. Commit 86910ff fixed the same thing in the GCP provider. This does it for the token exchange, the GitHub Actions provider and the AWS provider, the same way. The three descriptions are now these, each on one line: The request to the token endpoint at failed: . The GitHub Actions OIDC token endpoint at could not be reached: . This provider works only in a GitHub Actions job, which sets the endpoint in ACTIONS_ID_TOKEN_REQUEST_URL. The AWS STS endpoint at could not be reached: . `` is the cause in its own words, for example `[Errno -2] Name or service not known`, `[Errno 111] Connection refused`, `timed out` or `[SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1085)`. A cause with no text becomes `timed out` for a timeout and `unknown network error` otherwise, so the reason is never empty and never a class name. `` is the host of the URL, with its port when the URL names one. No user name, password, path or query of a URL is shown. Where the reason comes from: - Token exchange: the text of the httpx2 error. The sentence for `exchange_failed` still comes first. The assertion is redacted from the text, as it is from what the server sends. One kind of error is not quoted: a response that is not valid HTTP. Its text quotes the line the parser could not read, and with broken framing that line is the body, which holds the access token. That case reads `the server did not send a valid HTTP response`. - GitHub Actions: the `reason` of the `URLError`, or the error itself for a timeout while waiting for the response. - AWS: the error botocore keeps in `error`, followed to the operating system's error it was raised from. This covers a failed connection and a timeout (botocore's `ConnectionError` family and `ReadTimeoutError`). Every other botocore error keeps its message, `sts:GetWebIdentityToken failed with .`, because its text can quote the request, for example a header value. The asynchronous client words one case less exactly. For a refused connection its error says `All connection attempts failed`, where the synchronous client says `[Errno 111] Connection refused`. The operating system's error is not in that error's text or in its chain of causes. Nothing else changes. The codes are the same (`exchange_failed`, and `provider_failed` for the two providers), every failure is retried as before, and the exception types are the same. As before, none of these errors is chained to its cause: the transport error's request holds the assertion, and a provider's request holds its credentials. The tests cover a name that does not resolve, a refused connection and a timeout for each of the three, and check the whole description. For the exchange they run against both clients, and three of them leave the HTTP transport in place and open loopback sockets, so the wording is the real stack's. The AWS tests fake the name lookup or the connection under a real boto3 client, so nothing leaves the machine. --- .../workos_workload_identity_aws/__init__.py | 27 ++- .../tests/test_aws_sts.py | 121 +++++++++++ .../__init__.py | 24 ++- .../tests/test_github_actions.py | 114 +++++++++- src/workos/workload_identity.py | 46 +++- tests/test_workload_identity.py | 200 ++++++++++++++++++ 6 files changed, 519 insertions(+), 13 deletions(-) diff --git a/packages/workos-workload-identity-aws/src/workos_workload_identity_aws/__init__.py b/packages/workos-workload-identity-aws/src/workos_workload_identity_aws/__init__.py index 7e9baf0f..05ffed87 100644 --- a/packages/workos-workload-identity-aws/src/workos_workload_identity_aws/__init__.py +++ b/packages/workos-workload-identity-aws/src/workos_workload_identity_aws/__init__.py @@ -12,11 +12,13 @@ from __future__ import annotations +import urllib.parse from typing import TYPE_CHECKING, Callable, Optional import boto3 import botocore.session -from botocore.exceptions import BotoCoreError, ClientError +from botocore.exceptions import BotoCoreError, ClientError, ReadTimeoutError +from botocore.exceptions import ConnectionError as BotoConnectionError if TYPE_CHECKING: from types_boto3_sts.client import STSClient @@ -31,6 +33,25 @@ class AwsStsProviderError(Exception): """AWS STS did not return a web identity token.""" +def _unreachable(exc: BotoCoreError, endpoint_url: str) -> AwsStsProviderError: + """The error for a request that got no HTTP response, with the cause in words.""" + # botocore names only the URL it could not reach. It keeps the cause in + # ``error``: a urllib3 error, raised from the operating system's own. + cause: object = exc.kwargs.get("error") + while isinstance(cause, BaseException) and cause.__cause__ is not None: + cause = cause.__cause__ + reason = str(cause or "").strip() + if not reason: + reason = ( + "timed out" if isinstance(cause, TimeoutError) else "unknown network error" + ) + # Of the URL, only the host and port are shown. + host = urllib.parse.urlsplit(endpoint_url).netloc.rpartition("@")[2] + return AwsStsProviderError( + f"The AWS STS endpoint at {host} could not be reached: {reason}." + ) + + def _create_sts_client(region: Optional[str]) -> "STSClient": """Build an STS client on the regional endpoint for ``region``. @@ -86,6 +107,10 @@ def provider() -> str: raise AwsStsProviderError( f"sts:GetWebIdentityToken failed with {code}." ) from None + except (BotoConnectionError, ReadTimeoutError) as exc: + # No connection, or no answer. Any other failure of the AWS SDK + # keeps the message below: its text can quote the request. + raise _unreachable(exc, client.meta.endpoint_url) from None except BotoCoreError as exc: raise AwsStsProviderError( f"sts:GetWebIdentityToken failed with {type(exc).__name__}." diff --git a/packages/workos-workload-identity-aws/tests/test_aws_sts.py b/packages/workos-workload-identity-aws/tests/test_aws_sts.py index 661585f9..6be60205 100644 --- a/packages/workos-workload-identity-aws/tests/test_aws_sts.py +++ b/packages/workos-workload-identity-aws/tests/test_aws_sts.py @@ -5,11 +5,19 @@ The STS client is the real boto3 client with a botocore ``Stubber`` attached, so parameter names are validated against the service model and no request leaves the process. + +The tests of an unreachable endpoint have no stub. The client sends its +request, and the name lookup or the connection under it is faked, so nothing +leaves the machine. """ from __future__ import annotations import datetime +import errno +import os +import socket +import ssl from pathlib import Path from typing import TYPE_CHECKING, Callable, List, Optional @@ -24,6 +32,12 @@ AUDIENCE = "https://api.workos.com" EXPECTED_PARAMS = {"Audience": [AUDIENCE], "SigningAlgorithm": "RS256"} +STS_HOST = "sts.us-east-1.amazonaws.com" + + +def unreachable(reason: str) -> str: + """The whole error text for a request that got no HTTP response.""" + return f"The AWS STS endpoint at {STS_HOST} could not be reached: {reason}." @pytest.fixture(autouse=True) @@ -188,6 +202,113 @@ def test_WIF_AWS_02_missing_token_in_the_response_is_an_error(sts: StubbedSts) - provider() +@pytest.fixture +def resolves_to(monkeypatch: pytest.MonkeyPatch) -> Callable[[int], List[object]]: + """Point every host name at a loopback port, and list the names asked for.""" + # One attempt: botocore would sleep before each retry of a failed connection. + monkeypatch.setenv("AWS_MAX_ATTEMPTS", "1") + asked: List[object] = [] + + def resolve_to(port: int) -> List[object]: + def loopback(host: object, *args: object, **kwargs: object) -> List[object]: + asked.append(host) + address = ("127.0.0.1", port) + return [ + (socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", address) + ] + + monkeypatch.setattr(socket, "getaddrinfo", loopback) + return asked + + return resolve_to + + +def test_name_resolution_failure_names_the_reason( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setenv("AWS_MAX_ATTEMPTS", "1") + asked: List[object] = [] + + def no_such_name(host: object, *args: object, **kwargs: object) -> None: + asked.append(host) + raise socket.gaierror(-2, "Name or service not known") + + monkeypatch.setattr(socket, "getaddrinfo", no_such_name) + + with pytest.raises(AwsStsProviderError) as excinfo: + aws_sts(AUDIENCE, region="us-east-1")() + + assert str(excinfo.value) == unreachable("[Errno -2] Name or service not known") + assert asked == [STS_HOST] + + +def test_connection_refused_names_the_reason( + resolves_to: Callable[[int], List[object]], +) -> None: + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as closed: + closed.bind(("127.0.0.1", 0)) + port: int = closed.getsockname()[1] + asked = resolves_to(port) + + with pytest.raises(AwsStsProviderError) as excinfo: + aws_sts(AUDIENCE, region="us-east-1")() + + # The number differs by platform: 111 on Linux, 61 on macOS. + refused = f"[Errno {errno.ECONNREFUSED}] {os.strerror(errno.ECONNREFUSED)}" + assert refused.endswith("Connection refused") + assert str(excinfo.value) == unreachable(refused) + assert asked == [STS_HOST] + + +@pytest.mark.parametrize( + ("failure", "reason"), + [ + (TimeoutError("timed out"), "timed out"), + (TimeoutError(), "timed out"), + (OSError(), "unknown network error"), + ], + ids=["timeout", "timeout without text", "other failure without text"], +) +def test_connect_failure_always_names_a_reason( + resolves_to: Callable[[int], List[object]], + monkeypatch: pytest.MonkeyPatch, + failure: OSError, + reason: str, +) -> None: + def fail(self: socket.socket, address: object) -> None: + raise failure + + resolves_to(443) + monkeypatch.setattr(socket.socket, "connect", fail) + + with pytest.raises(AwsStsProviderError) as excinfo: + aws_sts(AUDIENCE, region="us-east-1")() + + assert str(excinfo.value) == unreachable(reason) + # Not chained: nothing of the request is reachable from the error. + assert excinfo.value.__cause__ is None + + +def test_timeout_waiting_for_the_response_names_the_reason( + resolves_to: Callable[[int], List[object]], monkeypatch: pytest.MonkeyPatch +) -> None: + def no_answer(*args: object, **kwargs: object) -> None: + raise TimeoutError("The read operation timed out") + + # A listener that never accepts: the connection opens through its backlog. + # The TLS handshake that would wait a minute for an answer is cut short. + monkeypatch.setattr(ssl.SSLContext, "wrap_socket", no_answer) + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as silent: + silent.bind(("127.0.0.1", 0)) + silent.listen(1) + resolves_to(silent.getsockname()[1]) + + with pytest.raises(AwsStsProviderError) as excinfo: + aws_sts(AUDIENCE, region="us-east-1")() + + assert str(excinfo.value) == unreachable("The read operation timed out") + + def test_audience_is_required() -> None: with pytest.raises(ValueError): aws_sts("", region="us-east-1") diff --git a/packages/workos-workload-identity-github-actions/src/workos_workload_identity_github_actions/__init__.py b/packages/workos-workload-identity-github-actions/src/workos_workload_identity_github_actions/__init__.py index 811d69e3..5b949c81 100644 --- a/packages/workos-workload-identity-github-actions/src/workos_workload_identity_github_actions/__init__.py +++ b/packages/workos-workload-identity-github-actions/src/workos_workload_identity_github_actions/__init__.py @@ -35,6 +35,26 @@ class GitHubActionsProviderError(Exception): """The GitHub Actions OIDC token could not be fetched.""" +def _unreachable(exc: OSError, url: str) -> GitHubActionsProviderError: + """The error for a request that got no HTTP response, with the cause in words.""" + # urllib wraps a failed connection in ``URLError`` and keeps the cause in + # ``reason``. A timeout while waiting for the response arrives unwrapped. + cause: object = exc.reason if isinstance(exc, urllib.error.URLError) else exc + reason = str(cause).strip() + if not reason: + reason = ( + "timed out" if isinstance(cause, TimeoutError) else "unknown network error" + ) + # Of the URL, only the host and port are shown: no user name, path or query. + host = urllib.parse.urlsplit(url).netloc.rpartition("@")[2] + at = f" at {host}" if host else "" + return GitHubActionsProviderError( + f"The GitHub Actions OIDC token endpoint{at} could not be reached: {reason}. " + "This provider works only in a GitHub Actions job, which sets the " + f"endpoint in {_URL_ENV}." + ) + + class _NoRedirect(urllib.request.HTTPRedirectHandler): """Turns every redirect into an ``HTTPError`` instead of following it.""" @@ -97,9 +117,7 @@ def provider() -> str: f"GitHub Actions OIDC token request failed with status {exc.code}." ) from None except OSError as exc: - raise GitHubActionsProviderError( - f"GitHub Actions OIDC token request failed: {type(exc).__name__}." - ) from None + raise _unreachable(exc, url) from None if status != 200: raise GitHubActionsProviderError( f"GitHub Actions OIDC token request failed with status {status}." diff --git a/packages/workos-workload-identity-github-actions/tests/test_github_actions.py b/packages/workos-workload-identity-github-actions/tests/test_github_actions.py index 56c179c6..993461ed 100644 --- a/packages/workos-workload-identity-github-actions/tests/test_github_actions.py +++ b/packages/workos-workload-identity-github-actions/tests/test_github_actions.py @@ -4,13 +4,17 @@ from __future__ import annotations +import errno import http.server +import os +import socket import threading from dataclasses import dataclass, field from typing import Dict, Iterator, List import pytest +import workos_workload_identity_github_actions as gha from workos_workload_identity_github_actions import ( GitHubActionsProviderError, github_actions, @@ -20,6 +24,15 @@ REQUEST_TOKEN = "gha-request-token" +def unreachable(reason: str, host: str) -> str: + """The whole error text for a request that got no HTTP response.""" + return ( + f"The GitHub Actions OIDC token endpoint at {host} could not be reached: " + f"{reason}. This provider works only in a GitHub Actions job, which sets " + "the endpoint in ACTIONS_ID_TOKEN_REQUEST_URL." + ) + + @dataclass class Recorded: method: str @@ -210,7 +223,106 @@ def test_connection_failure_is_a_provider_error( with pytest.raises(GitHubActionsProviderError) as excinfo: github_actions(AUDIENCE)() - assert REQUEST_TOKEN not in str(excinfo.value) + # The number differs by platform: 111 on Linux, 61 on macOS. + refused = f"[Errno {errno.ECONNREFUSED}] {os.strerror(errno.ECONNREFUSED)}" + assert refused.endswith("Connection refused") + assert str(excinfo.value) == unreachable(refused, unused.removeprefix("http://")) + + +def test_name_resolution_failure_names_the_reason( + monkeypatch: pytest.MonkeyPatch, +) -> None: + asked: List[object] = [] + + def no_such_name(host: object, *args: object, **kwargs: object) -> None: + asked.append(host) + raise socket.gaierror(-2, "Name or service not known") + + monkeypatch.setattr(socket, "getaddrinfo", no_such_name) + monkeypatch.setenv( + "ACTIONS_ID_TOKEN_REQUEST_URL", + "https://oidc.actions.invalid/token?api-version=2.0", + ) + monkeypatch.setenv("ACTIONS_ID_TOKEN_REQUEST_TOKEN", REQUEST_TOKEN) + + with pytest.raises(GitHubActionsProviderError) as excinfo: + github_actions(AUDIENCE)() + + assert str(excinfo.value) == unreachable( + "[Errno -2] Name or service not known", "oidc.actions.invalid" + ) + assert asked == ["oidc.actions.invalid"] + + +def test_timeout_waiting_for_the_response_names_the_reason( + monkeypatch: pytest.MonkeyPatch, +) -> None: + # A listener that never accepts: the connection opens through its backlog + # and no response ever comes. + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as silent: + silent.bind(("127.0.0.1", 0)) + silent.listen(1) + host = f"127.0.0.1:{silent.getsockname()[1]}" + monkeypatch.setenv("ACTIONS_ID_TOKEN_REQUEST_URL", f"http://{host}/token") + monkeypatch.setenv("ACTIONS_ID_TOKEN_REQUEST_TOKEN", REQUEST_TOKEN) + monkeypatch.setattr(gha, "_TIMEOUT_SECONDS", 0.2) + + with pytest.raises(GitHubActionsProviderError) as excinfo: + github_actions(AUDIENCE)() + + assert str(excinfo.value) == unreachable("timed out", host) + + +@pytest.mark.parametrize( + ("failure", "reason"), + [ + (TimeoutError("timed out"), "timed out"), + (TimeoutError(), "timed out"), + (OSError(), "unknown network error"), + ], + ids=["timeout", "timeout without text", "other failure without text"], +) +def test_connect_failure_always_names_a_reason( + monkeypatch: pytest.MonkeyPatch, failure: OSError, reason: str +) -> None: + def fail(*args: object, **kwargs: object) -> None: + raise failure + + monkeypatch.setattr(socket, "create_connection", fail) + monkeypatch.setenv( + "ACTIONS_ID_TOKEN_REQUEST_URL", "http://oidc.actions.invalid:8080/token" + ) + monkeypatch.setenv("ACTIONS_ID_TOKEN_REQUEST_TOKEN", REQUEST_TOKEN) + + with pytest.raises(GitHubActionsProviderError) as excinfo: + github_actions(AUDIENCE)() + + assert str(excinfo.value) == unreachable(reason, "oidc.actions.invalid:8080") + + +def test_unreachable_endpoint_shows_only_the_host_and_port_of_its_url( + monkeypatch: pytest.MonkeyPatch, +) -> None: + def refuse(*args: object, **kwargs: object) -> None: + raise ConnectionRefusedError(errno.ECONNREFUSED, "Connection refused") + + monkeypatch.setattr(socket, "create_connection", refuse) + monkeypatch.setenv( + "ACTIONS_ID_TOKEN_REQUEST_URL", + "http://url-user:url-password@oidc.actions.invalid:8080/url-path?url-query=1", + ) + monkeypatch.setenv("ACTIONS_ID_TOKEN_REQUEST_TOKEN", REQUEST_TOKEN) + + with pytest.raises(GitHubActionsProviderError) as excinfo: + github_actions(AUDIENCE)() + + assert str(excinfo.value) == unreachable( + f"[Errno {errno.ECONNREFUSED}] Connection refused", "oidc.actions.invalid:8080" + ) + # Not chained: nothing of the request is reachable from the error. + assert excinfo.value.__cause__ is None + for hidden in ("url-user", "url-password", "url-path", "url-query", REQUEST_TOKEN): + assert hidden not in repr(excinfo.value) def test_non_http_url_is_rejected(monkeypatch: pytest.MonkeyPatch) -> None: diff --git a/src/workos/workload_identity.py b/src/workos/workload_identity.py index 4c645a8f..4818eaa1 100644 --- a/src/workos/workload_identity.py +++ b/src/workos/workload_identity.py @@ -53,7 +53,13 @@ from ._base_client import MAX_RETRIES, _BaseWorkOSClient, _user_agent from ._credentials import CredentialSnapshot from ._errors import WorkOSError, WorkOSTimeoutError -from ._http import AsyncHttpxBackend, HTTPResponse, HttpxBackend, TransportError +from ._http import ( + AsyncHttpxBackend, + HTTPResponse, + HttpxBackend, + TransportError, + TransportTimeout, +) __all__ = [ "ENVIRONMENT_ID_HEADER", @@ -265,6 +271,30 @@ def _json_object(response: HTTPResponse) -> Optional[Dict[str, Any]]: return cast(Dict[str, Any], data) if isinstance(data, dict) else None +def _unreachable(error: TransportError, token_url: str) -> str: + """The description of a request that got no HTTP response: the host and the reason. + + The reason is the HTTP client's own text for the failure, which is mostly + the operating system's, such as ``[Errno 111] Connection refused``. It is + never empty and never a class name. Of the token URL, only the host and + port are shown. + """ + if isinstance(error.__cause__, httpx2.RemoteProtocolError): + # Its text can quote what the server sent, which may hold a token. + reason = "the server did not send a valid HTTP response" + else: + reason = str(error).strip() + if not reason: + # A timeout in the asynchronous client arrives with no text. + reason = ( + "timed out" + if isinstance(error, TransportTimeout) + else "unknown network error" + ) + host = httpx2.URL(token_url).netloc.decode("ascii") + return f"The request to the token endpoint at {host} failed: {reason}." + + def _exchange_headers() -> Dict[str, str]: # No Authorization header: the exchange carries no client secret and no API key. return { @@ -313,12 +343,12 @@ def provider_failed(self, error: Exception) -> None: self._description = str(error) or type(error).__name__ self._cause = error - def transport_failed(self, error: TransportError) -> None: - # Only the kind of failure: never the request, which holds the assertion. + def transport_failed( + self, error: TransportError, token_url: str, assertion: str + ) -> None: + # The reason in words, and no cause: the error's request holds the assertion. self._code = "exchange_failed" - self._description = ( - f"The request to the token endpoint failed ({type(error).__name__})." - ) + self._description = _redact(_unreachable(error, token_url), assertion) self._cause = None def exhausted(self) -> WorkloadIdentityError: @@ -816,7 +846,7 @@ def _exchange(self, deadline: float) -> Tuple[str, float]: timeout=run.attempt_timeout(attempt), ) except TransportError as error: - run.transport_failed(error) + run.transport_failed(error, self._token_url, assertion) continue result = run.read(response, assertion) if result is not None: @@ -845,7 +875,7 @@ async def _exchange_async(self, deadline: float) -> Tuple[str, float]: timeout=run.attempt_timeout(attempt), ) except TransportError as error: - run.transport_failed(error) + run.transport_failed(error, self._token_url, assertion) continue result = run.read(response, assertion) if result is not None: diff --git a/tests/test_workload_identity.py b/tests/test_workload_identity.py index 4cc55364..46315998 100644 --- a/tests/test_workload_identity.py +++ b/tests/test_workload_identity.py @@ -10,14 +10,21 @@ Nothing here touches the network. The token endpoint and the API are mocked at the httpx2 transport, below the client, so redirects, retries and headers are the real ones. Time is an injected clock, and backoff is an injected sleeper. + +The tests under "the real HTTP stack" are the exception. They leave the +transport in place, to see how a real failure to connect is worded, and open +loopback sockets only. """ from __future__ import annotations import asyncio +import errno import json import logging +import os import re +import socket import threading import time import traceback @@ -620,6 +627,11 @@ def secrets_in(error: BaseException, *secrets: str) -> List[str]: return found +def unreachable(reason: str, host: str = "token.test") -> str: + """The whole description of a token request that got no HTTP response.""" + return f"The request to the token endpoint at {host} failed: {reason}." + + # --- conformance cases --------------------------------------------------------------- @@ -1287,6 +1299,101 @@ def an_assertion_echoed_by_the_server_is_redacted(h: Harness) -> None: assert secrets_in(error, assertion) == [] +@scenario +def an_unreachable_token_endpoint_is_described_by_its_host_and_the_reason( + h: Harness, +) -> None: + refused = "[Errno 111] Connection refused" + untrusted = ( + "[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: " + "unable to get local issuer certificate (_ssl.c:1006)" + ) + # The error httpx2 raises, its text, and the reason the description gives. + failures = [ + (httpx2.ConnectError, "[Errno -2] Name or service not known", None), + (httpx2.ConnectError, refused, None), + (httpx2.ConnectError, "All connection attempts failed", None), + (httpx2.ConnectError, untrusted, None), + (httpx2.ConnectTimeout, "timed out", None), + (httpx2.ReadTimeout, "The read operation timed out", None), + # A timeout in the asynchronous client has no text. + (httpx2.ConnectTimeout, "", "timed out"), + (httpx2.ReadTimeout, "", "timed out"), + (httpx2.ReadError, "", "unknown network error"), + (httpx2.ReadError, "[Errno 104] Connection reset by peer", None), + ] + + for kind, text, reason in failures: + h.token.script.extend(kind(text) for _ in range(EXCHANGE_ATTEMPTS)) + error = h.failure(h.op_resolve(h.credentials())) + + assert isinstance(error, WorkloadIdentityError) + assert error.code == "exchange_failed" + assert error.description == unreachable(reason or text) + # The sentence for the code comes first, as for every other failure. + assert str(error) == ( + "exchange_failed: The token endpoint could not be reached or kept " + f"failing. Check the token URL and try again. {error.description}" + ) + # Not chained: the transport error's request holds the assertion. + assert error.__cause__ is None + + +@scenario +def an_unreachable_token_endpoint_shows_only_the_host_and_port_of_its_url( + h: Harness, +) -> None: + token_url = "https://url-user:url-password@token.test:8443/url-path?url-query=1" + h.token.script.extend( + httpx2.ConnectError("[Errno 111] Connection refused") + for _ in range(EXCHANGE_ATTEMPTS) + ) + + error = h.failure(h.op_resolve(h.credentials(token_url=token_url))) + + assert isinstance(error, WorkloadIdentityError) + assert error.description == unreachable( + "[Errno 111] Connection refused", host="token.test:8443" + ) + assert secrets_in(error, "url-user", "url-password", "url-path", "url-query") == [] + + +@scenario +def a_malformed_token_response_is_not_quoted(h: Harness) -> None: + # The HTTP parser quotes the line it could not read. When the framing is + # broken, that line is the body, which holds the access token. + access_token = "SECRET-ACCESS-VALUE" + body = '{"access_token":"' + access_token + '"}' + quoted = f"illegal chunk header: bytearray(b'{body}\\r\\n')" + h.token.script.extend( + httpx2.RemoteProtocolError(quoted) for _ in range(EXCHANGE_ATTEMPTS) + ) + + error = h.failure(h.op_resolve(h.credentials())) + + assert isinstance(error, WorkloadIdentityError) + assert error.code == "exchange_failed" + assert error.description == unreachable( + "the server did not send a valid HTTP response" + ) + assert secrets_in(error, access_token) == [] + + +@scenario +def an_assertion_in_a_transport_error_is_redacted(h: Harness) -> None: + assertion = "SECRET-ASSERTION-VALUE" + h.token.script.extend( + httpx2.ReadError(f"could not send {assertion}") + for _ in range(EXCHANGE_ATTEMPTS) + ) + + error = h.failure(h.op_resolve(h.credentials(Provider(assertion)))) + + assert isinstance(error, WorkloadIdentityError) + assert error.description == unreachable("could not send [redacted]") + assert secrets_in(error, assertion) == [] + + @scenario def a_long_error_description_is_cut_to_500_characters(h: Harness) -> None: h.token.script.append(oauth_error("invalid_grant", "x" * 2000)) @@ -1530,6 +1637,99 @@ def test_one_credentials_instance_serves_both_kinds_of_client( ] +# --- the real HTTP stack --------------------------------------------------------------- + +both_clients = pytest.mark.parametrize( + "asynchronous", [False, True], ids=["sync", "async"] +) + + +def real_failure(token_url: str, asynchronous: bool) -> WorkloadIdentityError: + """Exchange at ``token_url`` with nothing mocked, and return the error raised.""" + + async def no_sleep(seconds: float) -> None: + return None + + credentials = WorkloadIdentityCredentials( + client_id=CLIENT_ID, token_url=token_url, identity_token_provider=Provider() + ) + credentials._sleep = lambda seconds: None + credentials._async_sleep = no_sleep + with pytest.raises(WorkloadIdentityError) as raised: + if asynchronous: + asyncio.run(credentials.aresolve()) + else: + credentials.resolve() + assert raised.value.code == "exchange_failed" + assert raised.value.__cause__ is None + return raised.value + + +@both_clients +def test_a_token_host_that_does_not_resolve_names_the_reason( + asynchronous: bool, monkeypatch: pytest.MonkeyPatch +) -> None: + asked: List[object] = [] + + def no_such_name(host: object, *args: object, **kwargs: object) -> None: + asked.append(host.decode() if isinstance(host, bytes) else host) + raise socket.gaierror(-2, "Name or service not known") + + monkeypatch.setattr(socket, "getaddrinfo", no_such_name) + + error = real_failure("https://token.invalid:8443/oauth2/token", asynchronous) + + assert error.description == unreachable( + "[Errno -2] Name or service not known", host="token.invalid:8443" + ) + assert asked == ["token.invalid"] * EXCHANGE_ATTEMPTS + + +@both_clients +def test_a_token_endpoint_that_refuses_the_connection_names_the_reason( + asynchronous: bool, +) -> None: + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as closed: + closed.bind(("127.0.0.1", 0)) + host = f"127.0.0.1:{closed.getsockname()[1]}" + + error = real_failure(f"https://{host}/oauth2/token", asynchronous) + + # The number differs by platform: 111 on Linux, 61 on macOS. + refused = f"[Errno {errno.ECONNREFUSED}] {os.strerror(errno.ECONNREFUSED)}" + assert refused.endswith("Connection refused") + # The asynchronous client tries every address the host has and reports + # them as one failure. The operating system's error is not in its text. + reason = "All connection attempts failed" if asynchronous else refused + assert error.description == unreachable(reason, host=host) + + +@both_clients +def test_a_token_endpoint_that_does_not_answer_names_the_reason( + asynchronous: bool, monkeypatch: pytest.MonkeyPatch +) -> None: + # One short attempt: its timeout is a quarter of the deadline, and the + # backoff that would follow is longer than what is left. + monkeypatch.setattr(workload_identity, "EXCHANGE_DEADLINE_SECONDS", 0.6) + # A listener that never accepts: the connection opens through its backlog + # and the TLS handshake gets no answer. + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as silent: + silent.bind(("127.0.0.1", 0)) + silent.listen(1) + host = f"127.0.0.1:{silent.getsockname()[1]}" + + error = real_failure(f"https://{host}/oauth2/token", asynchronous) + + if asynchronous: + # The timeout has no text of its own here. + assert error.description == unreachable("timed out", host=host) + else: + # The interpreter's words, such as "The handshake operation timed out". + said = error.description + assert said.startswith(f"The request to the token endpoint at {host} failed: ") + assert said.endswith("timed out.") + + # --- configuration ------------------------------------------------------------------- From f3eca16510f7d4defb21fbe738ea219f1ebc86fb Mon Sep 17 00:00:00 2001 From: "Garen J. Torikian" Date: Sun, 22 Nov 2026 23:45:11 -0500 Subject: [PATCH 15/24] fix(workload-identity): Keep the GitHub Actions request token out of errors The GitHub Actions provider caught only `HTTPError` and `OSError` around its request. Any other error left the provider as it was, and the SDK copies the text of a provider's error into its own `provider_failed` error. With a line break at the end of `ACTIONS_ID_TOKEN_REQUEST_TOKEN`, the final error read: provider_failed: The identity token provider failed, so there was no token to exchange. Invalid header value b'Bearer \n' A provider must never put a token in an error, and the request token is a secret too. Other errors got out the same way. `InvalidURL` quotes the URL, `BadStatusLine` quotes what the server sent, and `IncompleteRead` holds the part of the body that arrived, which is the identity token. Two changes close this. First, the request token and the URL are checked before a request is built. A value with a character outside visible ASCII (0x21 to 0x7E) is refused with a fixed text that names the variable: ACTIONS_ID_TOKEN_REQUEST_TOKEN must not contain a space, a line break, another control character or a non-ASCII character. The value is not trimmed or repaired, the error shows no part of it, and no request is sent. Second, every error from sending the request or reading the response now leaves as a `GitHubActionsProviderError` with one of three fixed texts: ACTIONS_ID_TOKEN_REQUEST_URL is not a valid URL. GitHub Actions OIDC token response was not valid HTTP. GitHub Actions OIDC token request failed with an unexpected . Check ACTIONS_ID_TOKEN_REQUEST_URL and ACTIONS_ID_TOKEN_REQUEST_TOKEN. The first is for a URL that cannot be split into its parts, or whose port is not a number. The second is for any other `http.client.HTTPException`. The third is for everything else and names only the class of the error. None of them shows the error's own text. The three are raised outside the `except` blocks. `raise ... from None` inside a handler hides the caught error from a traceback and still leaves it attached as `__context__`, where its arguments can hold a token. Raised outside, the new error has nothing attached. JSON nested too deep to parse raised `RecursionError` out of the provider. It is now a response with no token value, like any other body that is not the expected JSON. Two kinds of value that used to be sent are now refused: - A request token with a space, a tab, a Latin-1 letter or a control character other than a line break. `http.client` sends those. - A URL with a line break, a tab or a space at the start. `urlsplit` drops them, so the request went out without them. A URL and a bearer token are visible ASCII, so a job on a GitHub runner should see no difference. The errors for a status other than 200 and for an endpoint that could not be reached are unchanged. The tests cover each case. They check that neither the request token nor the identity token is in the error's text, repr, arguments or attributes, or in any error attached to it as cause or context, and that a refused value sends no request. The responses that are not valid HTTP come from a loopback server that sends raw bytes, and each of those tests also shows which error urllib raises for the same bytes. --- .../__init__.py | 93 ++++-- .../tests/test_github_actions.py | 316 +++++++++++++++++- 2 files changed, 384 insertions(+), 25 deletions(-) diff --git a/packages/workos-workload-identity-github-actions/src/workos_workload_identity_github_actions/__init__.py b/packages/workos-workload-identity-github-actions/src/workos_workload_identity_github_actions/__init__.py index 5b949c81..2904b638 100644 --- a/packages/workos-workload-identity-github-actions/src/workos_workload_identity_github_actions/__init__.py +++ b/packages/workos-workload-identity-github-actions/src/workos_workload_identity_github_actions/__init__.py @@ -12,13 +12,14 @@ from __future__ import annotations +import http.client import json import os import urllib.error import urllib.parse import urllib.request from email.message import Message -from typing import IO, Callable +from typing import IO, Callable, Tuple __all__ = ["GitHubActionsProviderError", "github_actions"] @@ -29,6 +30,7 @@ "GitHub Actions did not provide an OIDC token endpoint. " "Add `permissions: id-token: write` to the workflow or job." ) +_INVALID_URL_MESSAGE = f"{_URL_ENV} is not a valid URL." class GitHubActionsProviderError(Exception): @@ -55,6 +57,19 @@ def _unreachable(exc: OSError, url: str) -> GitHubActionsProviderError: ) +def _require_visible_ascii(name: str, value: str) -> None: + """Refuse a value that has a character outside visible ASCII (0x21 to 0x7E). + + Neither a URL nor a bearer token has such a character. The value is not + repaired, and the error does not show it or any part of it. + """ + if any(not "!" <= char <= "~" for char in value): + raise GitHubActionsProviderError( + f"{name} must not contain a space, a line break, another control " + "character or a non-ASCII character." + ) + + class _NoRedirect(urllib.request.HTTPRedirectHandler): """Turns every redirect into an ``HTTPError`` instead of following it.""" @@ -75,7 +90,13 @@ def redirect_request( def _with_audience(url: str, audience: str) -> str: """Append ``audience`` to the URL's query string, keeping what is there.""" - parts = urllib.parse.urlsplit(url) + try: + parts = urllib.parse.urlsplit(url) + except ValueError: + # For example, a bracket of an IPv6 address that is never closed. + parts = None + if parts is None: + raise GitHubActionsProviderError(_INVALID_URL_MESSAGE) if parts.scheme not in ("http", "https"): raise GitHubActionsProviderError(f"{_URL_ENV} must be an http or https URL.") encoded = "audience=" + urllib.parse.quote(audience, safe="") @@ -83,6 +104,48 @@ def _with_audience(url: str, audience: str) -> str: return urllib.parse.urlunsplit(parts._replace(query=query)) +def _get(url: str, request_token: str) -> Tuple[int, bytes]: + """Send the token request and return the status and the body of the response. + + Every failure leaves as a ``GitHubActionsProviderError`` that shows nothing + of the request token. + """ + try: + request = urllib.request.Request( + url, + headers={ + "Authorization": f"Bearer {request_token}", + "Accept": "application/json", + }, + method="GET", + ) + with _OPENER.open(request, timeout=_TIMEOUT_SECONDS) as response: + status: int = response.status + body: bytes = response.read() + return status, body + except urllib.error.HTTPError as exc: + exc.close() + raise GitHubActionsProviderError( + f"GitHub Actions OIDC token request failed with status {exc.code}." + ) from None + except OSError as exc: + raise _unreachable(exc, url) from None + except http.client.InvalidURL: + message = _INVALID_URL_MESSAGE + except http.client.HTTPException: + message = "GitHub Actions OIDC token response was not valid HTTP." + except Exception as exc: + message = ( + "GitHub Actions OIDC token request failed with an unexpected " + f"{type(exc).__name__}. Check {_URL_ENV} and {_TOKEN_ENV}." + ) + # The text of these three kinds of error can quote the request token, the + # URL or what the server sent, so none of it is shown. The error is raised + # here, outside the handlers, so that the one that was caught is not kept + # as its context either. + raise GitHubActionsProviderError(message) from None + + def github_actions(audience: str) -> Callable[[], str]: """Return a provider of GitHub Actions OIDC tokens for ``audience``. @@ -98,26 +161,12 @@ def provider() -> str: request_token = os.environ.get(_TOKEN_ENV, "") if not url or not request_token: raise GitHubActionsProviderError(_MISSING_ENV_MESSAGE) + # Checked before a request is built. urllib would drop a line break + # from the URL, and would quote the request token in its own error. + _require_visible_ascii(_TOKEN_ENV, request_token) + _require_visible_ascii(_URL_ENV, url) - request = urllib.request.Request( - _with_audience(url, audience), - headers={ - "Authorization": f"Bearer {request_token}", - "Accept": "application/json", - }, - method="GET", - ) - try: - with _OPENER.open(request, timeout=_TIMEOUT_SECONDS) as response: - status: int = response.status - body: bytes = response.read() - except urllib.error.HTTPError as exc: - exc.close() - raise GitHubActionsProviderError( - f"GitHub Actions OIDC token request failed with status {exc.code}." - ) from None - except OSError as exc: - raise _unreachable(exc, url) from None + status, body = _get(_with_audience(url, audience), request_token) if status != 200: raise GitHubActionsProviderError( f"GitHub Actions OIDC token request failed with status {status}." @@ -125,7 +174,7 @@ def provider() -> str: try: payload = json.loads(body) - except ValueError: + except (ValueError, RecursionError): payload = None value = payload.get("value") if isinstance(payload, dict) else None # pyright: ignore[reportUnknownVariableType, reportUnknownMemberType] if not isinstance(value, str) or not value: diff --git a/packages/workos-workload-identity-github-actions/tests/test_github_actions.py b/packages/workos-workload-identity-github-actions/tests/test_github_actions.py index 993461ed..65ddef96 100644 --- a/packages/workos-workload-identity-github-actions/tests/test_github_actions.py +++ b/packages/workos-workload-identity-github-actions/tests/test_github_actions.py @@ -5,12 +5,15 @@ from __future__ import annotations import errno +import http.client import http.server import os import socket import threading +import urllib.parse +import urllib.request from dataclasses import dataclass, field -from typing import Dict, Iterator, List +from typing import Dict, Iterator, List, Optional, Type import pytest @@ -22,6 +25,21 @@ AUDIENCE = "https://api.workos.com" REQUEST_TOKEN = "gha-request-token" +IDENTITY_TOKEN = "gha-identity-jwt" +URL_ENV = "ACTIONS_ID_TOKEN_REQUEST_URL" +TOKEN_ENV = "ACTIONS_ID_TOKEN_REQUEST_TOKEN" + +# The fixed texts of the errors for a value or a response that cannot be used. +NOT_VISIBLE_ASCII = ( + "{name} must not contain a space, a line break, another control character " + "or a non-ASCII character." +) +INVALID_URL = f"{URL_ENV} is not a valid URL." +INVALID_RESPONSE = "GitHub Actions OIDC token response was not valid HTTP." +UNEXPECTED = ( + "GitHub Actions OIDC token request failed with an unexpected {kind}. " + f"Check {URL_ENV} and {TOKEN_ENV}." +) def unreachable(reason: str, host: str) -> str: @@ -89,6 +107,74 @@ def close(self) -> None: self._thread.join() +class RawServer: + """A loopback server that answers every connection with the same bytes. + + The bytes need not be HTTP, which ``http.server`` cannot be made to send. + """ + + def __init__(self, payload: bytes) -> None: + self._payload = payload + self._stop = threading.Event() + self._socket = socket.create_server(("127.0.0.1", 0)) + self._socket.settimeout(0.01) + self._thread = threading.Thread(target=self._serve, daemon=True) + self._thread.start() + + @property + def url(self) -> str: + return f"http://127.0.0.1:{self._socket.getsockname()[1]}/token" + + def _serve(self) -> None: + while not self._stop.is_set(): + try: + connection, _ = self._socket.accept() + except OSError: + continue + with connection: + connection.settimeout(5) + try: + received = b"" + while b"\r\n\r\n" not in received: + received += connection.recv(65536) or b"\r\n\r\n" + connection.sendall(self._payload) + # Closed only once the client has closed, so the client + # reads the answer and not a reset connection. + connection.shutdown(socket.SHUT_WR) + while connection.recv(65536): + pass + except OSError: + pass + + def close(self) -> None: + self._stop.set() + self._thread.join() + self._socket.close() + + +def shown(error: BaseException, *secrets: str) -> List[str]: + """Every place a secret shows up in an error or in an error attached to it.""" + found: List[str] = [] + seen: List[BaseException] = [] + current: Optional[BaseException] = error + while current is not None and current not in seen: + seen.append(current) + places = { + "str": str(current), + "repr": repr(current), + "args": repr(current.args), + "attributes": repr(vars(current)), + } + found.extend( + f"{type(current).__name__} {place}: {secret}" + for place, text in places.items() + for secret in secrets + if secret in text + ) + current = current.__cause__ or current.__context__ + return found + + @pytest.fixture def mock() -> Iterator[MockServer]: server = MockServer(body=b'{"value": "gha-jwt"}') @@ -185,8 +271,7 @@ def test_non_200_fails_naming_the_status(mock: MockServer) -> None: with pytest.raises(GitHubActionsProviderError, match="404") as excinfo: github_actions(AUDIENCE)() - assert REQUEST_TOKEN not in str(excinfo.value) - assert REQUEST_TOKEN not in repr(excinfo.value) + assert shown(excinfo.value, REQUEST_TOKEN) == [] @pytest.mark.usefixtures("actions_env") @@ -325,6 +410,231 @@ def refuse(*args: object, **kwargs: object) -> None: assert hidden not in repr(excinfo.value) +@pytest.mark.usefixtures("actions_env") +@pytest.mark.parametrize( + "request_token", + [ + f"{REQUEST_TOKEN}\n", + f"{REQUEST_TOKEN}\r\n", + f"{REQUEST_TOKEN}\r\nX-Added: 1", + f" {REQUEST_TOKEN}", + f"{REQUEST_TOKEN} {REQUEST_TOKEN}", + f"{REQUEST_TOKEN}\t", + f"{REQUEST_TOKEN}\x01", + f"{REQUEST_TOKEN}\x7f", + f"{REQUEST_TOKEN}\xe9", + f"{REQUEST_TOKEN}\u20ac", + f"{REQUEST_TOKEN}\udcff", + ], + ids=[ + "line break at the end", + "carriage return and line break", + "a second header line", + "space at the start", + "space inside", + "tab", + "control character", + "delete character", + "Latin-1 letter", + "character outside Latin-1", + "byte that is not UTF-8", + ], +) +def test_request_token_outside_visible_ascii_is_refused_before_any_request( + mock: MockServer, monkeypatch: pytest.MonkeyPatch, request_token: str +) -> None: + monkeypatch.setenv(TOKEN_ENV, request_token) + + with pytest.raises(GitHubActionsProviderError) as excinfo: + github_actions(AUDIENCE)() + + assert str(excinfo.value) == NOT_VISIBLE_ASCII.format(name=TOKEN_ENV) + assert shown(excinfo.value, REQUEST_TOKEN) == [] + assert mock.requests == [] + + +@pytest.mark.parametrize( + "url", + [ + "{mock}/to ken?api-version=2.0", + "{mock}/token?api-version=2.0\n", + "{mock}/tok\nen?api-version=2.0", + " {mock}/token?api-version=2.0", + "{mock}/token\t?api-version=2.0", + "{mock}/tok\xe9n?api-version=2.0", + "http://oidc actions.invalid/token?api-version=2.0", + ], + ids=[ + "space in the path", + "line break at the end", + "line break inside", + "space at the start", + "tab", + "non-ASCII letter", + "space in the host", + ], +) +def test_url_outside_visible_ascii_is_refused_before_any_request( + mock: MockServer, monkeypatch: pytest.MonkeyPatch, url: str +) -> None: + monkeypatch.setenv(URL_ENV, url.format(mock=mock.url)) + monkeypatch.setenv(TOKEN_ENV, REQUEST_TOKEN) + + with pytest.raises(GitHubActionsProviderError) as excinfo: + github_actions(AUDIENCE)() + + # urllib alone would drop the line breaks, the tab and the space at the + # start and send the request, and would quote the path with a space in it. + assert str(excinfo.value) == NOT_VISIBLE_ASCII.format(name=URL_ENV) + assert shown(excinfo.value, REQUEST_TOKEN, "api-version") == [] + assert mock.requests == [] + + +def test_url_with_a_port_that_is_not_a_number_is_not_a_valid_url( + monkeypatch: pytest.MonkeyPatch, +) -> None: + url = "http://127.0.0.1:url-port/url-path" + monkeypatch.setenv(URL_ENV, url) + monkeypatch.setenv(TOKEN_ENV, REQUEST_TOKEN) + + with pytest.raises(GitHubActionsProviderError) as excinfo: + github_actions(AUDIENCE)() + + assert str(excinfo.value) == INVALID_URL + assert shown(excinfo.value, REQUEST_TOKEN, "url-port", "url-path") == [] + # What urllib raises for it, and what that quotes. + with pytest.raises(http.client.InvalidURL, match="url-port"): + urllib.request.urlopen(url, timeout=1) + + +def test_url_that_cannot_be_split_is_not_a_valid_url( + monkeypatch: pytest.MonkeyPatch, +) -> None: + url = "http://[::1/url-path" + monkeypatch.setenv(URL_ENV, url) + monkeypatch.setenv(TOKEN_ENV, REQUEST_TOKEN) + + with pytest.raises(GitHubActionsProviderError) as excinfo: + github_actions(AUDIENCE)() + + assert str(excinfo.value) == INVALID_URL + assert shown(excinfo.value, REQUEST_TOKEN, "url-path") == [] + with pytest.raises(ValueError): + urllib.parse.urlsplit(url) + + +TOKEN_BODY = f'{{"value":"{IDENTITY_TOKEN}"}}'.encode() + + +@pytest.mark.parametrize( + ("payload", "underneath"), + [ + (TOKEN_BODY + b"\r\n\r\n", http.client.BadStatusLine), + ( + b"HTTP/1.1 200 OK\r\nContent-Length: 500\r\n\r\n" + TOKEN_BODY, + http.client.IncompleteRead, + ), + ( + b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n" + + TOKEN_BODY + + b"\r\n", + http.client.IncompleteRead, + ), + (b"HTTP/1.1 200 " + b"x" * 70000 + b"\r\n\r\n", http.client.LineTooLong), + ( + b"HTTP/1.1 200 OK\r\n" + b"X-Filler: 1\r\n" * 150 + b"\r\n", + http.client.HTTPException, + ), + (b"HTTP/9.9 200 OK\r\n\r\n", http.client.UnknownProtocol), + ], + ids=[ + "body where the status line belongs", + "body shorter than its Content-Length", + "body that is not chunked under a chunked header", + "status line too long", + "too many headers", + "unknown HTTP version", + ], +) +def test_response_that_is_not_valid_http_is_not_quoted( + monkeypatch: pytest.MonkeyPatch, payload: bytes, underneath: Type[Exception] +) -> None: + server = RawServer(payload) + monkeypatch.setenv(URL_ENV, server.url) + monkeypatch.setenv(TOKEN_ENV, REQUEST_TOKEN) + try: + with pytest.raises(GitHubActionsProviderError) as excinfo: + github_actions(AUDIENCE)() + # What urllib raises for the same answer. It holds the bytes received. + with pytest.raises(underneath): + with urllib.request.urlopen(server.url, timeout=5) as response: + response.read() + finally: + server.close() + + assert str(excinfo.value) == INVALID_RESPONSE + assert shown(excinfo.value, REQUEST_TOKEN, IDENTITY_TOKEN) == [] + + +@pytest.mark.parametrize( + ("ending", "kind"), + [("\n", "ValueError"), ("\u20ac", "UnicodeEncodeError")], + ids=["line break", "character outside Latin-1"], +) +def test_request_token_stays_out_of_the_error_without_the_character_check( + mock: MockServer, monkeypatch: pytest.MonkeyPatch, ending: str, kind: str +) -> None: + def no_check(name: str, value: str) -> None: + return None + + # With the check out of the way, http.client refuses the header itself, + # with an error that quotes the header value. + monkeypatch.setattr(gha, "_require_visible_ascii", no_check) + monkeypatch.setenv(URL_ENV, f"{mock.url}/token") + monkeypatch.setenv(TOKEN_ENV, REQUEST_TOKEN + ending) + + with pytest.raises(GitHubActionsProviderError) as excinfo: + github_actions(AUDIENCE)() + + assert str(excinfo.value) == UNEXPECTED.format(kind=kind) + assert shown(excinfo.value, REQUEST_TOKEN) == [] + assert mock.requests == [] + + +def test_host_name_that_cannot_be_encoded_is_a_provider_error( + monkeypatch: pytest.MonkeyPatch, +) -> None: + # A host name with an empty label. Encoding it for the name lookup fails + # before anything is looked up. + monkeypatch.setenv(URL_ENV, "http://url-host..invalid:8080/url-path") + monkeypatch.setenv(TOKEN_ENV, REQUEST_TOKEN) + + with pytest.raises(GitHubActionsProviderError) as excinfo: + github_actions(AUDIENCE)() + + # The class is UnicodeError before Python 3.13 and a subclass of it since. + assert str(excinfo.value) in ( + UNEXPECTED.format(kind="UnicodeError"), + UNEXPECTED.format(kind="UnicodeEncodeError"), + ) + assert shown(excinfo.value, REQUEST_TOKEN, "url-host", "url-path") == [] + + +def test_json_nested_too_deep_to_parse_has_no_token_value( + monkeypatch: pytest.MonkeyPatch, +) -> None: + body = b"[" * 100000 + head = f"HTTP/1.1 200 OK\r\nContent-Length: {len(body)}\r\n\r\n".encode() + server = RawServer(head + body) + monkeypatch.setenv(URL_ENV, server.url) + monkeypatch.setenv(TOKEN_ENV, REQUEST_TOKEN) + try: + with pytest.raises(GitHubActionsProviderError, match="no token value"): + github_actions(AUDIENCE)() + finally: + server.close() + + def test_non_http_url_is_rejected(monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setenv("ACTIONS_ID_TOKEN_REQUEST_URL", "file:///etc/hostname") monkeypatch.setenv("ACTIONS_ID_TOKEN_REQUEST_TOKEN", REQUEST_TOKEN) From 14383b22f3ad73a9926d9f9f36eff5738b4fb153 Mon Sep 17 00:00:00 2001 From: "Garen J. Torikian" Date: Sun, 22 Nov 2026 23:49:12 -0500 Subject: [PATCH 16/24] fix(workload-identity): Use the shared text for a refused request token Commit f3eca16 made the GitHub Actions provider refuse a request token or a URL that has a character outside visible ASCII. Its error listed the characters: ACTIONS_ID_TOKEN_REQUEST_TOKEN must not contain a space, a line break, another control character or a non-ASCII character. The Python, Kotlin and Elixir SDKs are to say the same thing for a refused request token. The text is now this, on one line: ACTIONS_ID_TOKEN_REQUEST_TOKEN contains a character that is not allowed in an HTTP header, such as a line break. GitHub Actions sets this variable; pass it to the program unchanged. It also says what to do: the runner sets the variable, so the fix is to hand it on as it is. The URL gets the matching text, because a sentence about an HTTP header does not fit it: ACTIONS_ID_TOKEN_REQUEST_URL contains a character that is not allowed in a URL, such as a space or a line break. GitHub Actions sets this variable; pass it to the program unchanged. Only the two texts change. Which values are refused is the same as in f3eca16, the value is still never shown, and no request is sent for a refused value. The tests compare both texts in full. --- .../__init__.py | 24 ++++++++++++------- .../tests/test_github_actions.py | 19 ++++++++++----- 2 files changed, 29 insertions(+), 14 deletions(-) diff --git a/packages/workos-workload-identity-github-actions/src/workos_workload_identity_github_actions/__init__.py b/packages/workos-workload-identity-github-actions/src/workos_workload_identity_github_actions/__init__.py index 2904b638..69a8193b 100644 --- a/packages/workos-workload-identity-github-actions/src/workos_workload_identity_github_actions/__init__.py +++ b/packages/workos-workload-identity-github-actions/src/workos_workload_identity_github_actions/__init__.py @@ -31,6 +31,17 @@ "Add `permissions: id-token: write` to the workflow or job." ) _INVALID_URL_MESSAGE = f"{_URL_ENV} is not a valid URL." +# For a value with a character outside visible ASCII. The value is not shown. +_UNUSABLE_TOKEN_MESSAGE = ( + f"{_TOKEN_ENV} contains a character that is not allowed in an HTTP header, " + "such as a line break. GitHub Actions sets this variable; pass it to the " + "program unchanged." +) +_UNUSABLE_URL_MESSAGE = ( + f"{_URL_ENV} contains a character that is not allowed in a URL, such as a " + "space or a line break. GitHub Actions sets this variable; pass it to the " + "program unchanged." +) class GitHubActionsProviderError(Exception): @@ -57,17 +68,14 @@ def _unreachable(exc: OSError, url: str) -> GitHubActionsProviderError: ) -def _require_visible_ascii(name: str, value: str) -> None: +def _require_visible_ascii(value: str, message: str) -> None: """Refuse a value that has a character outside visible ASCII (0x21 to 0x7E). Neither a URL nor a bearer token has such a character. The value is not - repaired, and the error does not show it or any part of it. + repaired, and ``message`` shows no part of it. """ if any(not "!" <= char <= "~" for char in value): - raise GitHubActionsProviderError( - f"{name} must not contain a space, a line break, another control " - "character or a non-ASCII character." - ) + raise GitHubActionsProviderError(message) class _NoRedirect(urllib.request.HTTPRedirectHandler): @@ -163,8 +171,8 @@ def provider() -> str: raise GitHubActionsProviderError(_MISSING_ENV_MESSAGE) # Checked before a request is built. urllib would drop a line break # from the URL, and would quote the request token in its own error. - _require_visible_ascii(_TOKEN_ENV, request_token) - _require_visible_ascii(_URL_ENV, url) + _require_visible_ascii(request_token, _UNUSABLE_TOKEN_MESSAGE) + _require_visible_ascii(url, _UNUSABLE_URL_MESSAGE) status, body = _get(_with_audience(url, audience), request_token) if status != 200: diff --git a/packages/workos-workload-identity-github-actions/tests/test_github_actions.py b/packages/workos-workload-identity-github-actions/tests/test_github_actions.py index 65ddef96..685fb8f1 100644 --- a/packages/workos-workload-identity-github-actions/tests/test_github_actions.py +++ b/packages/workos-workload-identity-github-actions/tests/test_github_actions.py @@ -30,9 +30,16 @@ TOKEN_ENV = "ACTIONS_ID_TOKEN_REQUEST_TOKEN" # The fixed texts of the errors for a value or a response that cannot be used. -NOT_VISIBLE_ASCII = ( - "{name} must not contain a space, a line break, another control character " - "or a non-ASCII character." +# The one for the request token is the same in every SDK that checks it. +UNUSABLE_TOKEN = ( + "ACTIONS_ID_TOKEN_REQUEST_TOKEN contains a character that is not allowed " + "in an HTTP header, such as a line break. GitHub Actions sets this " + "variable; pass it to the program unchanged." +) +UNUSABLE_URL = ( + "ACTIONS_ID_TOKEN_REQUEST_URL contains a character that is not allowed in " + "a URL, such as a space or a line break. GitHub Actions sets this " + "variable; pass it to the program unchanged." ) INVALID_URL = f"{URL_ENV} is not a valid URL." INVALID_RESPONSE = "GitHub Actions OIDC token response was not valid HTTP." @@ -448,7 +455,7 @@ def test_request_token_outside_visible_ascii_is_refused_before_any_request( with pytest.raises(GitHubActionsProviderError) as excinfo: github_actions(AUDIENCE)() - assert str(excinfo.value) == NOT_VISIBLE_ASCII.format(name=TOKEN_ENV) + assert str(excinfo.value) == UNUSABLE_TOKEN assert shown(excinfo.value, REQUEST_TOKEN) == [] assert mock.requests == [] @@ -485,7 +492,7 @@ def test_url_outside_visible_ascii_is_refused_before_any_request( # urllib alone would drop the line breaks, the tab and the space at the # start and send the request, and would quote the path with a space in it. - assert str(excinfo.value) == NOT_VISIBLE_ASCII.format(name=URL_ENV) + assert str(excinfo.value) == UNUSABLE_URL assert shown(excinfo.value, REQUEST_TOKEN, "api-version") == [] assert mock.requests == [] @@ -584,7 +591,7 @@ def test_response_that_is_not_valid_http_is_not_quoted( def test_request_token_stays_out_of_the_error_without_the_character_check( mock: MockServer, monkeypatch: pytest.MonkeyPatch, ending: str, kind: str ) -> None: - def no_check(name: str, value: str) -> None: + def no_check(value: str, message: str) -> None: return None # With the check out of the way, http.client refuses the header itself, From 0e7b70a670015d536af1dd450c9e94c9a503607a Mon Sep 17 00:00:00 2001 From: "Garen J. Torikian" Date: Mon, 23 Nov 2026 14:13:23 -0500 Subject: [PATCH 17/24] fix(workload-identity): Refuse a call that needs an API key as its client secret Some calls send the API key in the request body, as `client_secret`: the sign-in methods on `user_management`, `sso.get_profile_and_token` and `refresh()` on a session. A client built with `credentials` has no API key. Session refresh on such a client sent `"client_secret": null` with the workload identity token as the bearer, and turned any error that followed into a failed refresh. `_BaseWorkOSClient._client_secret(method)` is now the one place such a call reads the key: - A client with an API key gets the key. - A client with no API key and no credentials gets None, and the caller leaves the field out. That is a public client in a PKCE flow, which works as before. - A client built with credentials gets a `ConfigurationError`, before any request is sent and before any token exchange: needs an API key: this request sends it as the client secret. A client that authenticates with workload identity has no API key, so use a client built with one for this call. `Session.refresh` and `AsyncSession.refresh` read the key through it. They read it first, outside the `try` that turns an error into a failed refresh, so the error is raised and not returned. For a client with an API key and for a public client the request is the same as before. The generated sign-in and SSO methods still read the key directly. Generated files are not edited by hand; those methods call the accessor once the SDK is regenerated. The PKCE helpers `authenticate_with_code_pkce` and `get_profile_and_token_pkce` are not changed either. The README names the calls that need a client built with an API key. The tests cover the three cases of the accessor on both clients, a session refresh that is refused with no request and no exchange, the refresh request of a client with a key and of a public client, and a public client's PKCE code exchange. --- README.md | 2 + src/workos/_base_client.py | 21 +++++ src/workos/session.py | 26 +++++- tests/test_workload_identity.py | 137 ++++++++++++++++++++++++++++++++ 4 files changed, 182 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 053c5d73..3f1ea996 100644 --- a/README.md +++ b/README.md @@ -83,6 +83,8 @@ page = client.organizations.list_organizations() `AsyncWorkOSClient` takes the same `credentials` argument. Workload identity is used only when you pass `credentials`: no environment variable switches it on, `WORKOS_API_KEY` is ignored when credentials are passed, and a failed exchange is an error, never a fallback to an API key. Passing both `api_key` and `credentials` raises `ValueError`. +The calls that send the API key as the client secret still need a client built with `api_key`: the `user_management` sign-in methods such as `authenticate_with_password` and `authenticate_with_code`, `sso.get_profile_and_token`, and `refresh()` on a session. + | Argument | Environment variable | Description | |----------|----------------------|-------------| | `identity_token_provider` | | A callable that returns the workload's JWT (required) | diff --git a/src/workos/_base_client.py b/src/workos/_base_client.py index ed03a95f..12b55fb3 100644 --- a/src/workos/_base_client.py +++ b/src/workos/_base_client.py @@ -344,6 +344,27 @@ def _require_api_key(self) -> str: ) return self._api_key + def _client_secret(self, method: str) -> Optional[str]: + """The API key, for a request that sends it as ``client_secret``. + + ``method`` is the name of the calling method, used in the error. + + Returns None for a client that has no API key, such as a public client + in a PKCE flow; the caller then leaves the field out. A client that + authenticates with credentials has no API key either, and can never + make such a request, so this raises before anything is sent and before + any token exchange. + """ + if self._api_key: + return self._api_key + if self._credentials is not None: + raise ConfigurationError( + f"{method} needs an API key: this request sends it as the client " + "secret. A client that authenticates with workload identity has " + "no API key, so use a client built with one for this call." + ) + return None + def _require_client_id(self) -> str: if not self.client_id: raise ConfigurationError( diff --git a/src/workos/session.py b/src/workos/session.py index 41dd7143..14624021 100644 --- a/src/workos/session.py +++ b/src/workos/session.py @@ -339,7 +339,16 @@ def refresh( RefreshWithSessionCookieSuccessResponse, RefreshWithSessionCookieErrorResponse, ]: - """Refresh the session using the stored refresh token.""" + """Refresh the session using the stored refresh token. + + Raises: + ConfigurationError: The client authenticates with workload identity + credentials. The refresh request sends the API key as the + client secret, and that client has none. + """ + # Read first, and outside the ``try`` below, so that a client with no + # API key to send is an error and not a failed refresh. + client_secret = self._client._client_secret("refresh") effective_cookie_password = cookie_password or self.cookie_password try: @@ -360,7 +369,7 @@ def refresh( body: Dict[str, Any] = { "grant_type": "refresh_token", "client_id": self._client.client_id, - "client_secret": self._client._api_key, + "client_secret": client_secret, "refresh_token": session["refresh_token"], } if organization_id is not None: @@ -555,7 +564,16 @@ async def refresh( RefreshWithSessionCookieSuccessResponse, RefreshWithSessionCookieErrorResponse, ]: - """Refresh the session using the stored refresh token.""" + """Refresh the session using the stored refresh token. + + Raises: + ConfigurationError: The client authenticates with workload identity + credentials. The refresh request sends the API key as the + client secret, and that client has none. + """ + # Read first, and outside the ``try`` below, so that a client with no + # API key to send is an error and not a failed refresh. + client_secret = self._client._client_secret("refresh") effective_cookie_password = cookie_password or self.cookie_password try: @@ -576,7 +594,7 @@ async def refresh( body: Dict[str, Any] = { "grant_type": "refresh_token", "client_id": self._client.client_id, - "client_secret": self._client._api_key, + "client_secret": client_secret, "refresh_token": session["refresh_token"], } if organization_id is not None: diff --git a/tests/test_workload_identity.py b/tests/test_workload_identity.py index 46315998..079efb55 100644 --- a/tests/test_workload_identity.py +++ b/tests/test_workload_identity.py @@ -35,7 +35,9 @@ import httpx2 import pytest +from cryptography.fernet import Fernet +from tests.generated_helpers import load_fixture from workos import ( AsyncWorkOSClient, AuthenticationError, @@ -52,6 +54,9 @@ from workos import workload_identity from workos._credentials import StaticKeyCredentials, apply_snapshot from workos._errors import ConfigurationError, WorkOSTimeoutError +from workos.session import seal_data +from workos.sso.models import SSOTokenResponse +from workos.user_management.models import AuthenticateResponse CLIENT_ID = "client_wif_test" ENVIRONMENT_ID = "environment_wif_test" @@ -1488,6 +1493,138 @@ def a_workload_identity_client_cannot_start_the_feature_flags_runtime( client.create_feature_flags_runtime_client() +# --- the API key as the client secret ------------------------------------------------- +# +# The sign-in calls, the SSO code exchange and session refresh send the API key +# in the request body, as ``client_secret``. They read it through +# ``_client_secret``. + +COOKIE_PASSWORD = Fernet.generate_key().decode("utf-8") + + +def client_secret_error(method: str) -> str: + return ( + f"{method} needs an API key: this request sends it as the client secret. " + "A client that authenticates with workload identity has no API key, so " + "use a client built with one for this call." + ) + + +def load_session(client: Any) -> Any: + """A session of ``client`` whose sealed cookie holds a refresh token.""" + sealed = seal_data( + {"refresh_token": "rt_old", "user": {"id": "user_01"}}, COOKIE_PASSWORD + ) + return client.user_management.load_sealed_session( + session_data=sealed, cookie_password=COOKIE_PASSWORD + ) + + +@scenario +def the_client_secret_is_the_api_key_of_a_client_that_has_one(h: Harness) -> None: + client = h.client(api_key="sk_test_static", client_id=CLIENT_ID) + + assert client._client_secret("authenticate_with_password") == "sk_test_static" + + +@scenario +def a_client_with_no_api_key_and_no_credentials_leaves_the_client_secret_out( + h: Harness, +) -> None: + # A public client in a PKCE flow. None tells the caller to send no field. + for client in ( + h.client(client_id=CLIENT_ID), + h.client(client_id=CLIENT_ID, is_public=True), + ): + assert client._client_secret("authenticate_with_code") is None + + +@scenario +def a_workload_identity_client_has_no_client_secret_to_send(h: Harness) -> None: + provider = Provider() + client = h.client(h.credentials(provider)) + + with pytest.raises(ConfigurationError) as caught: + client._client_secret("authenticate_with_password") + + assert str(caught.value) == client_secret_error("authenticate_with_password") + assert provider.calls == 0 + assert h.token.count == 0 + assert h.api.count == 0 + + +@scenario +def a_workload_identity_client_cannot_refresh_a_session(h: Harness) -> None: + provider = Provider() + client = h.client(h.credentials(provider), client_id=CLIENT_ID) + session = load_session(client) + + # Raised, not returned as a failed refresh, and before anything is sent. + error = h.failure(lambda: session.refresh()) + + assert isinstance(error, ConfigurationError) + assert str(error) == client_secret_error("refresh") + assert provider.calls == 0 + assert h.token.count == 0 + assert h.api.count == 0 + + +@scenario +def session_refresh_is_unchanged_for_a_client_without_credentials(h: Harness) -> None: + with_key = h.client(api_key="sk_test_static", client_id=CLIENT_ID) + h.run(lambda: load_session(with_key).refresh()) + body = json.loads(h.api.requests[-1].content) + assert body["client_secret"] == "sk_test_static" + assert body["refresh_token"] == "rt_old" + + public = h.client(client_id=CLIENT_ID, is_public=True) + h.run(lambda: load_session(public).refresh()) + body = json.loads(h.api.requests[-1].content) + assert body.get("client_secret") is None + assert body["refresh_token"] == "rt_old" + assert "authorization" not in h.api.requests[-1].headers + + assert h.api.count == 2 + assert h.token.count == 0 + + +@scenario +def a_public_client_still_exchanges_a_code_with_pkce(h: Harness) -> None: + client = h.client(client_id=CLIENT_ID, is_public=True) + h.api.script.append(Reply(200, load_fixture("authenticate_response.json"))) + h.api.script.append(Reply(200, load_fixture("sso_token_response.json"))) + + authenticated = h.run( + lambda: client.user_management.authenticate_with_code_pkce( + code="code-1", code_verifier="verifier-1" + ) + ) + profile = h.run( + lambda: client.sso.get_profile_and_token_pkce( + code="code-2", code_verifier="verifier-2" + ) + ) + + assert isinstance(authenticated, AuthenticateResponse) + assert isinstance(profile, SSOTokenResponse) + assert [json.loads(request.content) for request in h.api.requests] == [ + { + "grant_type": "authorization_code", + "client_id": CLIENT_ID, + "code": "code-1", + "code_verifier": "verifier-1", + }, + { + "client_id": CLIENT_ID, + "code": "code-2", + "grant_type": "authorization_code", + "code_verifier": "verifier-2", + }, + ] + assert h.api.bearers() == [None, None] + assert h.token.count == 0 + + # --- one client only ----------------------------------------------------------------- From 7efacdcdc9748e5688999883041c229ab63bd273 Mon Sep 17 00:00:00 2001 From: "Garen J. Torikian" Date: Mon, 23 Nov 2026 16:23:48 -0500 Subject: [PATCH 18/24] fix(workload-identity): Keep the GCP identity token out of errors for a broken response The GCP provider caught `HTTPError` and `OSError` around its request. A response that is not valid HTTP raises `http.client.HTTPException`, which is neither, so it left the provider as it was. For a response that is cut short, that is `IncompleteRead`, and its arguments hold the bytes that arrived, which are part of the identity token: IncompleteRead(25 bytes read, 475 more expected) args: (b'',) The SDK keeps a provider's error as the cause of its own `provider_failed` error, so those bytes travel with it to anything that records attached errors. Every error from sending the request or reading the response now leaves as a `GcpMetadataProviderError`, as in the GitHub Actions provider. Two fixed texts are new: GCP metadata identity response was not valid HTTP. GCP metadata identity request failed with an unexpected . The first is for any `http.client.HTTPException`. The second is for everything else and names only the class of the error. Neither shows the error's own text. Both are raised outside the `except` blocks, so the error that was caught is not attached as context either. The errors for a status other than 200, for an empty body and for a server that could not be reached are unchanged. The tests answer the request with raw bytes from a loopback server: the token where the status line belongs, a body shorter than its Content-Length, a body that is not chunked under a chunked header, a status line that is too long, too many headers and an unknown HTTP version. They check that the token is not in the error's text, repr, arguments or attributes, or in any error attached to it, and each one also shows which error urllib raises for the same bytes. --- .../workos_workload_identity_gcp/__init__.py | 56 ++++--- .../tests/test_gcp_metadata.py | 142 +++++++++++++++++- 2 files changed, 180 insertions(+), 18 deletions(-) diff --git a/packages/workos-workload-identity-gcp/src/workos_workload_identity_gcp/__init__.py b/packages/workos-workload-identity-gcp/src/workos_workload_identity_gcp/__init__.py index f5849f7c..24d10fbf 100644 --- a/packages/workos-workload-identity-gcp/src/workos_workload_identity_gcp/__init__.py +++ b/packages/workos-workload-identity-gcp/src/workos_workload_identity_gcp/__init__.py @@ -12,11 +12,12 @@ from __future__ import annotations +import http.client import urllib.error import urllib.parse import urllib.request from email.message import Message -from typing import IO, Callable +from typing import IO, Callable, Tuple __all__ = ["GcpMetadataProviderError", "gcp_metadata"] @@ -64,6 +65,42 @@ def redirect_request( return None +def _get(opener: urllib.request.OpenerDirector, url: str) -> Tuple[int, bytes]: + """Send the identity request and return the status and the body of the response. + + Every failure leaves as a ``GcpMetadataProviderError`` that shows nothing + of the identity token. + """ + try: + request = urllib.request.Request( + url, headers={"Metadata-Flavor": "Google"}, method="GET" + ) + with opener.open(request, timeout=_TIMEOUT_SECONDS) as response: + status: int = response.status + body: bytes = response.read() + return status, body + except urllib.error.HTTPError as exc: + exc.close() + raise GcpMetadataProviderError( + f"GCP metadata identity request failed with status {exc.code}." + ) from None + except OSError as exc: + raise _unreachable(exc) from None + except http.client.HTTPException: + message = "GCP metadata identity response was not valid HTTP." + except Exception as exc: + message = ( + "GCP metadata identity request failed with an unexpected " + f"{type(exc).__name__}." + ) + # These two kinds of error can hold what the server sent: the text of a + # ``BadStatusLine`` quotes it, and an ``IncompleteRead`` keeps the bytes + # that arrived, which are part of the identity token. So none of it is + # shown. The error is raised here, outside the handlers, so that the one + # that was caught is not kept as its context either. + raise GcpMetadataProviderError(message) from None + + def gcp_metadata(audience: str) -> Callable[[], str]: """Return a provider of GCP metadata-server identity tokens for ``audience``. @@ -78,22 +115,7 @@ def gcp_metadata(audience: str) -> Callable[[], str]: opener = urllib.request.build_opener(_NoRedirect, urllib.request.ProxyHandler({})) def provider() -> str: - request = urllib.request.Request( - f"{_METADATA_BASE_URL}{_IDENTITY_PATH}?{query}", - headers={"Metadata-Flavor": "Google"}, - method="GET", - ) - try: - with opener.open(request, timeout=_TIMEOUT_SECONDS) as response: - status: int = response.status - body: bytes = response.read() - except urllib.error.HTTPError as exc: - exc.close() - raise GcpMetadataProviderError( - f"GCP metadata identity request failed with status {exc.code}." - ) from None - except OSError as exc: - raise _unreachable(exc) from None + status, body = _get(opener, f"{_METADATA_BASE_URL}{_IDENTITY_PATH}?{query}") if status != 200: raise GcpMetadataProviderError( f"GCP metadata identity request failed with status {status}." diff --git a/packages/workos-workload-identity-gcp/tests/test_gcp_metadata.py b/packages/workos-workload-identity-gcp/tests/test_gcp_metadata.py index c6491388..c871aa75 100644 --- a/packages/workos-workload-identity-gcp/tests/test_gcp_metadata.py +++ b/packages/workos-workload-identity-gcp/tests/test_gcp_metadata.py @@ -5,12 +5,14 @@ from __future__ import annotations import errno +import http.client import http.server import os import socket import threading +import urllib.request from dataclasses import dataclass, field -from typing import Dict, Iterator, List +from typing import Dict, Iterator, List, Optional, Type import pytest @@ -19,6 +21,9 @@ AUDIENCE = "https://api.workos.com" IDENTITY_PATH = "/computeMetadata/v1/instance/service-accounts/default/identity" +IDENTITY_TOKEN = "SECRET-GCP-IDENTITY-TOKEN" +INVALID_RESPONSE = "GCP metadata identity response was not valid HTTP." +UNEXPECTED = "GCP metadata identity request failed with an unexpected {kind}." def unreachable(reason: str) -> str: @@ -86,6 +91,74 @@ def close(self) -> None: self._thread.join() +class RawServer: + """A loopback server that answers every connection with the same bytes. + + The bytes need not be HTTP, which ``http.server`` cannot be made to send. + """ + + def __init__(self, payload: bytes) -> None: + self._payload = payload + self._stop = threading.Event() + self._socket = socket.create_server(("127.0.0.1", 0)) + self._socket.settimeout(0.01) + self._thread = threading.Thread(target=self._serve, daemon=True) + self._thread.start() + + @property + def url(self) -> str: + return f"http://127.0.0.1:{self._socket.getsockname()[1]}" + + def _serve(self) -> None: + while not self._stop.is_set(): + try: + connection, _ = self._socket.accept() + except OSError: + continue + with connection: + connection.settimeout(5) + try: + received = b"" + while b"\r\n\r\n" not in received: + received += connection.recv(65536) or b"\r\n\r\n" + connection.sendall(self._payload) + # Closed only once the client has closed, so the client + # reads the answer and not a reset connection. + connection.shutdown(socket.SHUT_WR) + while connection.recv(65536): + pass + except OSError: + pass + + def close(self) -> None: + self._stop.set() + self._thread.join() + self._socket.close() + + +def shown(error: BaseException, *secrets: str) -> List[str]: + """Every place a secret shows up in an error or in an error attached to it.""" + found: List[str] = [] + seen: List[BaseException] = [] + current: Optional[BaseException] = error + while current is not None and current not in seen: + seen.append(current) + places = { + "str": str(current), + "repr": repr(current), + "args": repr(current.args), + "attributes": repr(vars(current)), + } + found.extend( + f"{type(current).__name__} {place}: {secret}" + for place, text in places.items() + for secret in secrets + if secret in text + ) + current = current.__cause__ or current.__context__ + return found + + @pytest.fixture def mock(monkeypatch: pytest.MonkeyPatch) -> Iterator[MockServer]: """The metadata server. The provider's internal base URL points at it.""" @@ -244,6 +317,73 @@ def test_WIF_GCP_03_the_request_does_not_go_through_an_environment_proxy( assert len(mock.requests) == 1 +TOKEN_BODY = IDENTITY_TOKEN.encode() + + +@pytest.mark.parametrize( + ("payload", "underneath"), + [ + (TOKEN_BODY + b"\r\n\r\n", http.client.BadStatusLine), + ( + b"HTTP/1.1 200 OK\r\nContent-Length: 500\r\n\r\n" + TOKEN_BODY, + http.client.IncompleteRead, + ), + ( + b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n" + + TOKEN_BODY + + b"\r\n", + http.client.IncompleteRead, + ), + (b"HTTP/1.1 200 " + b"x" * 70000 + b"\r\n\r\n", http.client.LineTooLong), + ( + b"HTTP/1.1 200 OK\r\n" + b"X-Filler: 1\r\n" * 150 + b"\r\n", + http.client.HTTPException, + ), + (b"HTTP/9.9 200 OK\r\n\r\n", http.client.UnknownProtocol), + ], + ids=[ + "token where the status line belongs", + "token shorter than its Content-Length", + "token that is not chunked under a chunked header", + "status line too long", + "too many headers", + "unknown HTTP version", + ], +) +def test_response_that_is_not_valid_http_is_not_quoted( + monkeypatch: pytest.MonkeyPatch, payload: bytes, underneath: Type[Exception] +) -> None: + server = RawServer(payload) + monkeypatch.setattr(gcp, "_METADATA_BASE_URL", server.url) + try: + with pytest.raises(GcpMetadataProviderError) as excinfo: + gcp_metadata(AUDIENCE)() + # What urllib raises for the same answer. It holds the bytes received. + with pytest.raises(underneath): + with urllib.request.urlopen(server.url, timeout=5) as response: + response.read() + finally: + server.close() + + assert str(excinfo.value) == INVALID_RESPONSE + assert shown(excinfo.value, IDENTITY_TOKEN) == [] + + +def test_an_unexpected_error_is_named_and_not_quoted( + monkeypatch: pytest.MonkeyPatch, +) -> None: + def fail(*args: object, **kwargs: object) -> None: + raise ValueError(f"something that quotes {IDENTITY_TOKEN}") + + monkeypatch.setattr(urllib.request.OpenerDirector, "open", fail) + + with pytest.raises(GcpMetadataProviderError) as excinfo: + gcp_metadata(AUDIENCE)() + + assert str(excinfo.value) == UNEXPECTED.format(kind="ValueError") + assert shown(excinfo.value, IDENTITY_TOKEN) == [] + + def test_audience_is_percent_encoded(mock: MockServer) -> None: gcp_metadata("api://workos/prod env")() From 37db2a94ec2ccdaa67a15a4846c42f0c8089bff1 Mon Sep 17 00:00:00 2001 From: "Garen J. Torikian" Date: Mon, 23 Nov 2026 16:23:48 -0500 Subject: [PATCH 19/24] fix(workload-identity): Share one exchange between synchronous and asynchronous callers One `WorkloadIdentityCredentials` can serve a `WorkOSClient` and an `AsyncWorkOSClient` at once, and coroutines on more than one event loop. It kept two in-flight exchanges, one for threads and one for tasks, and a task of another event loop was never joined. So callers that arrived together could start two exchanges. With `token_file` or `token_env` both send the same identity token, the server accepts it once, and one caller fails with `invalid_grant`. There is now one in-flight exchange per instance, with one shared result. A thread runs it when a synchronous caller starts it, a task when an asynchronous caller does, and a caller of either kind waits for it: a thread blocks on an event, and a coroutine is woken on its own event loop, so no loop is blocked. A caller joins an exchange only when it can count on an answer. A task runs only while its event loop runs, so in two cases a caller starts an exchange of its own instead of joining: - A synchronous call made on the thread of the event loop that runs the exchange. Blocking that thread would stop the exchange it waits for. - A caller on another thread, when the exchange belongs to an event loop that is not running. Both cases started an exchange of their own before this change too. A task that is canceled now fails its exchange with `exchange_failed` and the description "The exchange was canceled before it finished.", so callers on other threads and loops are not left waiting. A coroutine that waits for an exchange gives it up one second after the exchange's deadline, as a thread already did. A second change is in the same function. An exchange that a waiter gave up at its deadline could still finish later, and its token then replaced the one a newer exchange had stored. An exchange that was given up has failed, so what it returns afterwards is now dropped. The tests: a coroutine joins an exchange that a thread runs, a thread joins an exchange that a task runs, and a coroutine on a second event loop joins it, each with one POST to the token endpoint and one call of the provider. A blocking call on the loop that runs the exchange returns instead of waiting for it. A task canceled before its first step fails its waiter at once. An exchange given up at its deadline does not publish the token it gets afterwards. --- src/workos/workload_identity.py | 216 +++++++++++++++++++++---------- tests/test_workload_identity.py | 217 +++++++++++++++++++++++++++++++- 2 files changed, 362 insertions(+), 71 deletions(-) diff --git a/src/workos/workload_identity.py b/src/workos/workload_identity.py index 4818eaa1..41b8b255 100644 --- a/src/workos/workload_identity.py +++ b/src/workos/workload_identity.py @@ -40,6 +40,7 @@ Awaitable, Callable, Dict, + List, Optional, Protocol, Tuple, @@ -95,6 +96,7 @@ _DEADLINE_DESCRIPTION = ( f"The exchange did not finish within {EXCHANGE_DEADLINE_SECONDS:g} seconds." ) +_CANCELED_DESCRIPTION = "The exchange was canceled before it finished." _WAIT_TIMEOUT_MESSAGE = "Timed out waiting for the workload identity token exchange." # --- errors --------------------------------------------------------------------- @@ -408,17 +410,27 @@ def read( return access_token, _lifetime(body.get("expires_in")) -class _SyncExchange: - """One in-flight exchange started by the synchronous path, and its shared result.""" +class _Exchange: + """One in-flight exchange and its result, shared by every caller that waits for it. - __slots__ = ("deadline", "done", "error", "result", "settled") + A thread runs the exchange when a synchronous caller starts it, and a task + on the caller's event loop when an asynchronous caller does. Either kind + of caller can wait for either: a thread waits on ``done``, and a coroutine + is woken through ``wakers``. + """ + + __slots__ = ("deadline", "done", "error", "result", "settled", "task", "wakers") def __init__(self, deadline: float) -> None: self.deadline = deadline + # The task that runs the exchange. None when a thread runs it. + self.task: Optional["asyncio.Task[None]"] = None self.done = threading.Event() self.settled = False self.result: Optional[Tuple[str, int]] = None self.error: Optional[BaseException] = None + # One per waiting coroutine. Each wakes its own event loop. + self.wakers: List[Callable[[], None]] = [] def outcome(self) -> Tuple[str, int]: if self.error is not None: @@ -427,11 +439,12 @@ def outcome(self) -> Tuple[str, int]: return self.result -def _retrieve_exception(task: "asyncio.Task[Tuple[str, int]]") -> None: - # Marks a failed exchange's exception as seen, so asyncio does not log - # "Task exception was never retrieved" when every waiter has given up. - if not task.cancelled(): - task.exception() +def _running_loop() -> Optional[asyncio.AbstractEventLoop]: + """The event loop running in this thread, or None when there is none.""" + try: + return asyncio.get_running_loop() + except RuntimeError: + return None # --- credentials ---------------------------------------------------------------- @@ -464,8 +477,9 @@ class WorkloadIdentityCredentials: The access token is cached on this instance, in memory only, and refreshed on demand once less than ``min(60 seconds, 20% of its lifetime)`` remains. - Concurrent callers share one exchange. Two instances never share a token, - even with identical settings. + Concurrent callers share one exchange, whether they come from a + synchronous client, an asynchronous one, or both. Two instances never + share a token, even with identical settings. Settings are fixed at construction; build a new instance to change one. An omitted ``client_id`` falls back to ``WORKOS_CLIENT_ID``, the only @@ -534,10 +548,9 @@ def __init__( self._expires_at = -math.inf self._lifetime = 0.0 self._generation = 0 - # In-flight exchanges. The two kinds of client wait in different ways, - # so each has its own: a thread for sync callers, a task for async ones. - self._inflight: Optional[_SyncExchange] = None - self._async_inflight: Optional["asyncio.Task[Tuple[str, int]]"] = None + # The exchange in flight. Callers of both kinds of client wait for the + # same one, whichever kind started it. + self._inflight: Optional[_Exchange] = None # Seams for tests: the clock that decides freshness, and the sleeps # between exchange attempts. @@ -615,12 +628,10 @@ async def aresolve(self, *, timeout: Optional[float] = None) -> CredentialSnapsh """ with self._lock: current = self._fresh() - if current is None: - task = self._join_or_start_async() - try: - current = await asyncio.wait_for(asyncio.shield(task), timeout) - except asyncio.TimeoutError: - raise WorkOSTimeoutError(_WAIT_TIMEOUT_MESSAGE) from None + exchange = None if current is not None else self._join_or_start_async() + if exchange is not None: + current = await self._wait_async(exchange, timeout) + assert current is not None return self._snapshot(*current) def invalidate(self, generation: int) -> None: @@ -663,13 +674,34 @@ def _store(self, token: str, lifetime: float) -> int: self._generation += 1 return self._generation - # --- shared exchange, synchronous callers --- + # --- shared exchange --- + + def _can_join(self, exchange: _Exchange, *, blocking: bool) -> bool: + """Whether a caller can wait for ``exchange`` and count on an answer. Lock held. - def _join_or_start(self) -> _SyncExchange: - """The exchange in progress, started if there is none. Lock held.""" + ``blocking`` is true for a synchronous caller, which blocks its thread + while it waits. + """ + task = exchange.task + if task is None: + # A thread runs it, whatever its waiters do. + return True + if task.done(): + # Canceled before it ran a single step, so it never settled. + return False + runner = task.get_loop() + if runner is _running_loop(): + # The caller is on the loop that runs the exchange. A coroutine + # that awaits lets it run. A blocked thread would stop it. + return not blocking + # Another thread's loop. It runs the exchange only while it is running. + return runner.is_running() + + def _join_or_start(self) -> _Exchange: + """The exchange in progress, started on a thread if there is none. Lock held.""" exchange = self._inflight - if exchange is None: - exchange = _SyncExchange(time.monotonic() + EXCHANGE_DEADLINE_SECONDS) + if exchange is None or not self._can_join(exchange, blocking=True): + exchange = _Exchange(time.monotonic() + EXCHANGE_DEADLINE_SECONDS) self._inflight = exchange try: # Its own thread, not the first caller's: a caller that gives up @@ -685,7 +717,23 @@ def _join_or_start(self) -> _SyncExchange: raise return exchange - def _run_exchange(self, exchange: _SyncExchange) -> None: + def _join_or_start_async(self) -> _Exchange: + """The exchange in progress, started as a task if there is none. Lock held.""" + exchange = self._inflight + if exchange is None or not self._can_join(exchange, blocking=False): + exchange = _Exchange(time.monotonic() + EXCHANGE_DEADLINE_SECONDS) + # A task of its own, not the first caller's, for the same reason. + task = asyncio.get_running_loop().create_task( + self._run_exchange_async(exchange) + ) + exchange.task = task + # A task canceled before its first step never reaches its own + # ``except``; this settles the exchange for it. + task.add_done_callback(lambda _: self._settle_canceled(exchange)) + self._inflight = exchange + return exchange + + def _run_exchange(self, exchange: _Exchange) -> None: try: token, lifetime = self._exchange(exchange.deadline) except BaseException as error: @@ -693,9 +741,36 @@ def _run_exchange(self, exchange: _SyncExchange) -> None: return self._settle(exchange, token=token, lifetime=lifetime) + async def _run_exchange_async(self, exchange: _Exchange) -> None: + try: + try: + token, lifetime = await asyncio.wait_for( + self._exchange_async(exchange.deadline), EXCHANGE_DEADLINE_SECONDS + ) + except asyncio.TimeoutError: + raise WorkloadIdentityError( + "exchange_failed", _DEADLINE_DESCRIPTION + ) from None + except Exception as error: + self._settle(exchange, error=error) + except BaseException: + # Canceled, as when its event loop shuts down. Callers on other + # threads and loops may be waiting, so they are told. + self._settle_canceled(exchange) + raise + else: + self._settle(exchange, token=token, lifetime=lifetime) + + def _settle_canceled(self, exchange: _Exchange) -> None: + """Fail an exchange whose task ended without an outcome. No effect otherwise.""" + self._settle( + exchange, + error=WorkloadIdentityError("exchange_failed", _CANCELED_DESCRIPTION), + ) + def _settle( self, - exchange: _SyncExchange, + exchange: _Exchange, *, token: Optional[str] = None, lifetime: float = 0.0, @@ -706,24 +781,28 @@ def _settle( The in-flight slot is cleared before anyone is woken, so a caller that gets an error and calls again starts a new exchange. On success the token is stored under the same lock that clears the slot. + + Only the first outcome counts. An exchange that a waiter gave up at its + deadline has failed, and a token it comes back with later is dropped: + by then a newer exchange may have stored a token of its own. """ with self._lock: - generation = self._store(token, lifetime) if token is not None else 0 if self._inflight is exchange: self._inflight = None if exchange.settled: - # A waiter already gave this exchange up at its deadline. return exchange.settled = True if token is not None: - exchange.result = (token, generation) + exchange.result = (token, self._store(token, lifetime)) else: exchange.error = error + # No waker is added once the exchange is settled. + wakers = exchange.wakers exchange.done.set() + for wake in wakers: + wake() - def _wait( - self, exchange: _SyncExchange, timeout: Optional[float] - ) -> Tuple[str, int]: + def _wait(self, exchange: _Exchange, timeout: Optional[float]) -> Tuple[str, int]: overdue_at = exchange.deadline + _DEADLINE_GRACE_SECONDS budget = overdue_at - time.monotonic() patience = budget if timeout is None else min(timeout, budget) @@ -732,9 +811,10 @@ def _wait( if time.monotonic() < overdue_at: # This caller's own timeout. The exchange is left alone. raise WorkOSTimeoutError(_WAIT_TIMEOUT_MESSAGE) - # The exchange outran its deadline, which only a provider that does not - # return can cause: a thread cannot be interrupted. Give it up so the - # next caller starts a new exchange instead of waiting on this one. + # The exchange outran its deadline: a provider that does not return (a + # thread cannot be interrupted), or a task whose event loop stopped. + # Give it up so the next caller starts a new exchange instead of + # waiting on this one. self._settle( exchange, error=WorkloadIdentityError("exchange_failed", _DEADLINE_DESCRIPTION), @@ -742,42 +822,40 @@ def _wait( exchange.done.wait() return exchange.outcome() - # --- shared exchange, asynchronous callers --- - - def _join_or_start_async(self) -> "asyncio.Task[Tuple[str, int]]": + async def _wait_async( + self, exchange: _Exchange, timeout: Optional[float] + ) -> Tuple[str, int]: + """Asynchronous twin of :meth:`_wait`. It never blocks the event loop.""" loop = asyncio.get_running_loop() + woken = asyncio.Event() + + def wake() -> None: + # Called by whichever thread settles the exchange. + try: + loop.call_soon_threadsafe(woken.set) + except RuntimeError: + # This waiter's loop has closed. Nobody is waiting on it. + pass + with self._lock: - task = self._async_inflight - # A task is bound to its event loop; one left by another loop, or - # canceled before it ever ran, cannot be joined. - if task is None or task.done() or task.get_loop() is not loop: - task = loop.create_task(self._run_exchange_async()) - task.add_done_callback(_retrieve_exception) - self._async_inflight = task - return task - - async def _run_exchange_async(self) -> Tuple[str, int]: - task = asyncio.current_task() - deadline = time.monotonic() + EXCHANGE_DEADLINE_SECONDS + if exchange.settled: + return exchange.outcome() + exchange.wakers.append(wake) + overdue_at = exchange.deadline + _DEADLINE_GRACE_SECONDS + budget = overdue_at - time.monotonic() + patience = budget if timeout is None else min(timeout, budget) try: - try: - token, lifetime = await asyncio.wait_for( - self._exchange_async(deadline), EXCHANGE_DEADLINE_SECONDS - ) - except asyncio.TimeoutError: - raise WorkloadIdentityError( - "exchange_failed", _DEADLINE_DESCRIPTION - ) from None - with self._lock: - generation = self._store(token, lifetime) - if self._async_inflight is task: - self._async_inflight = None - return token, generation - finally: - # Cleared on every path, before any waiter sees the outcome. - with self._lock: - if self._async_inflight is task: - self._async_inflight = None + await asyncio.wait_for(woken.wait(), max(patience, 0.0)) + except asyncio.TimeoutError: + if time.monotonic() < overdue_at: + # This caller's own timeout. The exchange is left alone. + raise WorkOSTimeoutError(_WAIT_TIMEOUT_MESSAGE) from None + # As in _wait: given up, so the next caller starts a new exchange. + self._settle( + exchange, + error=WorkloadIdentityError("exchange_failed", _DEADLINE_DESCRIPTION), + ) + return exchange.outcome() # --- the exchange itself --- diff --git a/tests/test_workload_identity.py b/tests/test_workload_identity.py index 079efb55..24f7333f 100644 --- a/tests/test_workload_identity.py +++ b/tests/test_workload_identity.py @@ -102,6 +102,17 @@ def response(self) -> httpx2.Response: return httpx2.Response(self.status, json=self.json, headers=self.headers) +@dataclass +class HeldReply(Reply): + """A response that is not sent until ``release`` is set.""" + + release: threading.Event = field(default_factory=threading.Event) + + def response(self) -> httpx2.Response: + assert self.release.wait(10), "a held reply was never released" + return super().response() + + def oauth_error(code: str, description: str = "the server said no") -> Reply: return Reply(400, {"error": code, "error_description": description}) @@ -1661,6 +1672,47 @@ def test_sync_waiter_times_out_without_failing_the_exchange( assert h.token.count == 1 +def test_an_exchange_given_up_at_its_deadline_does_not_publish_a_late_token( + sync_harness: Harness, +) -> None: + h = sync_harness + usual_deadline = workload_identity.EXCHANGE_DEADLINE_SECONDS + h.monkeypatch.setattr(workload_identity, "EXCHANGE_DEADLINE_SECONDS", 0.3) + h.monkeypatch.setattr(workload_identity, "_DEADLINE_GRACE_SECONDS", 0.01) + late = HeldReply( + 200, {"access_token": "access-late", "token_type": "Bearer", "expires_in": 300} + ) + h.token.script.append(late) + credentials = h.credentials() + before = threading.enumerate() + + try: + # The first exchange is still waiting for its response at the deadline. + waiter = h.start(h.op_resolve(credentials)) + h.wait_until(h.token.entered.is_set) + abandoned = [t for t in threading.enumerate() if t not in before] + error = h.outcome(waiter) + assert isinstance(error, WorkloadIdentityError) + assert "did not finish" in error.description + + # The next one succeeds and stores its token. + h.monkeypatch.setattr( + workload_identity, "EXCHANGE_DEADLINE_SECONDS", usual_deadline + ) + current = h.resolve(credentials) + assert current.headers["Authorization"] == "Bearer access-1" + finally: + late.release.set() + # The first exchange now gets its response. It failed at the deadline, so + # the token it comes back with replaces nothing. + for thread in abandoned: + thread.join(10) + assert not thread.is_alive() + + assert h.resolve(credentials) == current + assert h.token.count == 2 + + def test_async_client_awaits_a_coroutine_provider(async_harness: Harness) -> None: h = async_harness threads: List[int] = [] @@ -1737,17 +1789,47 @@ def test_async_exchange_canceled_before_it_ran_does_not_block_the_next( h = async_harness credentials = h.credentials() - async def never_runs() -> Any: + async def never_runs() -> None: raise AssertionError("canceled before its first step") stale = h.loop.create_task(never_runs()) stale.cancel() h.outcome(stale) - credentials._async_inflight = stale + exchange = workload_identity._Exchange(time.monotonic() + 30) + exchange.task = stale + credentials._inflight = exchange assert h.resolve(credentials).headers["Authorization"] == "Bearer access-1" +def test_an_async_exchange_canceled_before_it_ran_fails_its_waiters_at_once( + async_harness: AsyncHarness, +) -> None: + h = async_harness + credentials = h.credentials() + + async def cancel_the_exchange_before_its_first_step() -> Any: + waiter = h.loop.create_task(credentials.aresolve()) + # One turn of the loop: the waiter has created the task that runs the + # exchange, and that task has not run yet. + await asyncio.sleep(0) + exchange = credentials._inflight + assert exchange is not None and exchange.task is not None + exchange.task.cancel() + return (await asyncio.gather(waiter, return_exceptions=True))[0] + + error = h.loop.run_until_complete( + asyncio.wait_for(cancel_the_exchange_before_its_first_step(), 10) + ) + + # Its waiter is told, and does not wait for the deadline to find out. + assert isinstance(error, WorkloadIdentityError) + assert error.code == "exchange_failed" + assert "canceled" in error.description + assert h.token.count == 0 + assert h.resolve(credentials).headers["Authorization"] == "Bearer access-1" + + def test_one_credentials_instance_serves_both_kinds_of_client( sync_harness: Harness, async_harness: Harness ) -> None: @@ -1774,6 +1856,137 @@ def test_one_credentials_instance_serves_both_kinds_of_client( ] +def beside_an_async_exchange( + h: AsyncHarness, client: Any, joins: Counter, second: Operation +) -> List[Any]: + """Run ``second`` on a thread while ``client``'s exchange is held back. + + The event loop keeps running throughout, as it does in an application. + Returns the outcome of the asynchronous request, then that of ``second``. + """ + + async def scene() -> List[Any]: + first = h.loop.create_task(client.request("GET", ("organizations",))) + while not h.token.entered.is_set(): + await asyncio.sleep(0.001) + other = _ThreadCaller(second) + other.thread.start() + while joins.value < 2: + await asyncio.sleep(0.001) + h.token.release() + outcome = (await asyncio.gather(first, return_exceptions=True))[0] + while other.thread.is_alive(): + await asyncio.sleep(0.001) + return [outcome, other.outcome] + + return h.loop.run_until_complete(asyncio.wait_for(scene(), 10)) + + +def test_a_coroutine_joins_the_exchange_a_thread_runs( + sync_harness: Harness, async_harness: Harness +) -> None: + provider = Provider() + credentials = sync_harness.credentials(provider) + joins = sync_harness.watch_joins(credentials) + sync_client = sync_harness.client(credentials) + async_client = async_harness.client(credentials) + token = sync_harness.token + token.hold() + + blocking = sync_harness.start(sync_harness.op_request(sync_client)) + sync_harness.wait_until(token.entered.is_set) + awaiting = async_harness.start(async_harness.op_request(async_client)) + async_harness.wait_until(lambda: joins.value == 2) + token.release() + + assert async_harness.outcome(awaiting) == {"ok": True} + assert sync_harness.outcome(blocking) == {"ok": True} + assert token.count == 1 + assert provider.calls == 1 + assert sync_harness.api.bearers() == ["access-1", "access-1"] + + +def test_a_thread_joins_the_exchange_a_task_runs( + sync_harness: Harness, async_harness: AsyncHarness +) -> None: + provider = Provider() + credentials = async_harness.credentials(provider) + joins = async_harness.watch_joins(credentials) + sync_client = sync_harness.client(credentials) + async_client = async_harness.client(credentials) + async_harness.token.hold() + + outcomes = beside_an_async_exchange( + async_harness, async_client, joins, sync_harness.op_request(sync_client) + ) + + assert outcomes == [{"ok": True}, {"ok": True}] + assert async_harness.token.count == 1 + assert provider.calls == 1 + assert async_harness.api.bearers() == ["access-1", "access-1"] + + +def test_a_coroutine_on_another_event_loop_joins_the_exchange( + async_harness: AsyncHarness, +) -> None: + h = async_harness + provider = Provider() + credentials = h.credentials(provider) + joins = h.watch_joins(credentials) + client = h.client(credentials) + h.token.hold() + + def on_another_loop() -> Any: + async def request() -> Any: + async with AsyncWorkOSClient( + base_url=API_URL, credentials=credentials + ) as other: + return await other.request("GET", ("organizations",)) + + return asyncio.run(request()) + + outcomes = beside_an_async_exchange(h, client, joins, on_another_loop) + + assert outcomes == [{"ok": True}, {"ok": True}] + assert h.token.count == 1 + assert provider.calls == 1 + assert h.api.bearers() == ["access-1", "access-1"] + + +def test_a_blocking_call_on_the_loop_that_runs_the_exchange_does_not_wait_for_it( + sync_harness: Harness, async_harness: AsyncHarness +) -> None: + # A synchronous client called from a coroutine blocks the event loop. The + # exchange a task of that loop runs cannot finish until the call returns, + # so the call exchanges for itself instead of waiting for it. + credentials = async_harness.credentials() + sync_client = sync_harness.client(credentials) + async_client = async_harness.client(credentials) + token = async_harness.token + token.hold() + + async def scene() -> List[Any]: + first = async_harness.loop.create_task( + async_client.request("GET", ("organizations",)) + ) + while not token.entered.is_set(): + await asyncio.sleep(0.001) + # Nothing on this loop runs during the blocking call, so a timer on a + # thread of its own lets the token endpoint answer. + threading.Timer(0.05, token.release).start() + blocked = sync_client.request("GET", ("organizations",)) + return [blocked, await first] + + outcomes = async_harness.loop.run_until_complete(asyncio.wait_for(scene(), 10)) + + assert outcomes == [{"ok": True}, {"ok": True}] + assert token.count == 2 + assert sorted(str(bearer) for bearer in async_harness.api.bearers()) == [ + "access-1", + "access-2", + ] + + # --- the real HTTP stack --------------------------------------------------------------- both_clients = pytest.mark.parametrize( From 8de554563bf1f70825abcdfc6d6a7c4c908df4a4 Mon Sep 17 00:00:00 2001 From: "Garen J. Torikian" Date: Mon, 23 Nov 2026 16:50:34 -0500 Subject: [PATCH 20/24] fix(workload-identity): Run every token exchange on a thread of its own Commit 37db2a9 made synchronous and asynchronous callers share one exchange. An exchange that an asynchronous caller started was still a task on that caller's event loop, and a task runs only while its loop runs. One case was left where two exchanges ran: a synchronous client called from a coroutine blocks the event loop, so it could not wait for a task of that loop and exchanged for itself. With `token_file` or `token_env` the second exchange sends the same identity token, and the server refuses it with `invalid_grant`. Every exchange now runs on a thread of its own, whichever kind of client starts it. It depends on no caller's thread and on no event loop, so any caller can wait for it: a thread blocks on an event, and a coroutine is woken on its own loop. The blocking call inside a coroutine joins the exchange that is in flight, and one POST reaches the token endpoint. What stays as it was: - A plain provider may block. It runs on the exchange's thread, never on an event loop. - An `async def` provider is awaited on the event loop of the asynchronous caller that started the exchange. - A synchronous caller with an `async def` provider is refused with `provider_failed` and the text "The identity token provider is asynchronous. Use it with AsyncWorkOSClient, or pass a synchronous provider." It is now refused before it joins or starts an exchange, so it cannot block the loop the provider needs. - A caller that is canceled or times out stops waiting, and the exchange goes on for the others. What changes: - The exchange is sent with the synchronous HTTP stack for both clients. It reads the same settings as the asynchronous stack did: each was a client of its own with the library's defaults, so the proxy settings and the CA bundle come from the same environment variables, and TLS verification is on. An unreachable token endpoint is now described the same way for both clients, with the operating system's reason, such as "[Errno 111] Connection refused". The asynchronous client used to say "All connection attempts failed" for a refused connection and "timed out" for a timeout. - An exchange outlives the event loop of the caller that started it. - A plain callable that returns an awaitable is known to be asynchronous only once it is called. If a blocking call holds the loop that awaitable needs, the exchange waits for it until its deadline and then fails with `provider_failed` for every waiter. No second exchange is started. The thread is a daemon and ends when the exchange does. Nothing is kept per credentials object between exchanges, and an exchange in flight does not keep the interpreter alive. The asynchronous twin of the exchange is removed, and with it the two cases in which 37db2a9 fell back to a second exchange. Tests: a blocking call on the event loop joins the exchange that a coroutine started, with one POST. A blocking call with an `async def` provider fails at once, and the exchange in flight still succeeds. A blocking call ends at the deadline when the provider needs the loop it blocks. An exchange survives the cancellation of the caller that started it, and the closing of that caller's event loop. The thread of an exchange is a daemon and ends with the exchange, and a script that exits with an exchange in flight does exit. Two tests of the real HTTP stack expected the asynchronous wording for a refused connection and for a timeout; they now expect the same text for both clients. The test for a task that is canceled before its first step is replaced, because there is no task. --- src/workos/workload_identity.py | 242 +++++++++++---------------- tests/test_workload_identity.py | 278 +++++++++++++++++++++++--------- 2 files changed, 301 insertions(+), 219 deletions(-) diff --git a/src/workos/workload_identity.py b/src/workos/workload_identity.py index 41b8b255..607407fe 100644 --- a/src/workos/workload_identity.py +++ b/src/workos/workload_identity.py @@ -30,6 +30,7 @@ from __future__ import annotations import asyncio +import concurrent.futures import inspect import math import os @@ -55,7 +56,6 @@ from ._credentials import CredentialSnapshot from ._errors import WorkOSError, WorkOSTimeoutError from ._http import ( - AsyncHttpxBackend, HTTPResponse, HttpxBackend, TransportError, @@ -96,7 +96,13 @@ _DEADLINE_DESCRIPTION = ( f"The exchange did not finish within {EXCHANGE_DEADLINE_SECONDS:g} seconds." ) -_CANCELED_DESCRIPTION = "The exchange was canceled before it finished." +_ASYNC_PROVIDER_MESSAGE = ( + "The identity token provider is asynchronous. Use it with " + "AsyncWorkOSClient, or pass a synchronous provider." +) +_PROVIDER_TIMEOUT_MESSAGE = ( + "The identity token provider did not return before the exchange's deadline." +) _WAIT_TIMEOUT_MESSAGE = "Timed out waiting for the workload identity token exchange." # --- errors --------------------------------------------------------------------- @@ -188,8 +194,9 @@ class IdentityTokenProvider(Protocol): """A callable that returns the workload's JWT. Called once per exchange attempt; it may return the same token each time. - A plain function may block: the asynchronous client runs it in a worker - thread. A coroutine function is awaited (asynchronous client only). + A plain function may block: it runs on the exchange's own thread, never on + an event loop. A coroutine function is awaited on the event loop of the + asynchronous client that started the exchange (asynchronous client only). """ def __call__(self) -> Union[str, Awaitable[str]]: ... @@ -238,6 +245,30 @@ def _is_coroutine_callable(provider: object) -> bool: ) +def _await_on( + loop: asyncio.AbstractEventLoop, awaitable: Awaitable[object], timeout: float +) -> object: + """Await ``awaitable`` on ``loop`` from another thread, for at most ``timeout`` seconds.""" + + async def relay() -> object: + return await awaitable + + coroutine = relay() + try: + future = asyncio.run_coroutine_threadsafe(coroutine, loop) + except RuntimeError: + # The loop has closed, so nothing will ever await these two. + coroutine.close() + if inspect.iscoroutine(awaitable): + awaitable.close() + raise + try: + return future.result(timeout) + except concurrent.futures.TimeoutError: + future.cancel() + raise TimeoutError(_PROVIDER_TIMEOUT_MESSAGE) from None + + def _require_token(value: object) -> str: if not isinstance(value, str): raise TypeError( @@ -287,7 +318,7 @@ def _unreachable(error: TransportError, token_url: str) -> str: else: reason = str(error).strip() if not reason: - # A timeout in the asynchronous client arrives with no text. + # Some timeouts arrive with no text. reason = ( "timed out" if isinstance(error, TransportTimeout) @@ -323,6 +354,10 @@ def remaining(self) -> float: raise WorkloadIdentityError("exchange_failed", _DEADLINE_DESCRIPTION) return remaining + def time_left(self) -> float: + """Seconds left before the deadline, or zero when it has passed.""" + return max(self._deadline - time.monotonic(), 0.0) + def attempt_timeout(self, attempt: int) -> float: """The HTTP timeout for ``attempt``: an even share of the time left. @@ -413,18 +448,21 @@ def read( class _Exchange: """One in-flight exchange and its result, shared by every caller that waits for it. - A thread runs the exchange when a synchronous caller starts it, and a task - on the caller's event loop when an asynchronous caller does. Either kind - of caller can wait for either: a thread waits on ``done``, and a coroutine - is woken through ``wakers``. + The exchange runs on a thread of its own, so it depends on no caller's + thread and on no event loop. A synchronous caller blocks on ``done``. An + asynchronous caller is woken on its own event loop through ``wakers``. """ - __slots__ = ("deadline", "done", "error", "result", "settled", "task", "wakers") + __slots__ = ("deadline", "done", "error", "loop", "result", "settled", "wakers") - def __init__(self, deadline: float) -> None: + def __init__( + self, deadline: float, loop: Optional[asyncio.AbstractEventLoop] + ) -> None: self.deadline = deadline - # The task that runs the exchange. None when a thread runs it. - self.task: Optional["asyncio.Task[None]"] = None + # The event loop of the asynchronous caller that started the exchange, + # where an asynchronous provider is awaited. None when a synchronous + # caller started it. + self.loop = loop self.done = threading.Event() self.settled = False self.result: Optional[Tuple[str, int]] = None @@ -439,14 +477,6 @@ def outcome(self) -> Tuple[str, int]: return self.result -def _running_loop() -> Optional[asyncio.AbstractEventLoop]: - """The event loop running in this thread, or None when there is none.""" - try: - return asyncio.get_running_loop() - except RuntimeError: - return None - - # --- credentials ---------------------------------------------------------------- @@ -535,6 +565,8 @@ def __init__( "identity_token_provider is required and must be callable", ) self._provider = identity_token_provider + # Only an asynchronous caller can start an exchange with such a provider. + self._provider_is_async = _is_coroutine_callable(identity_token_provider) self._client_id = self._required("client_id", client_id, _CLIENT_ID_ENV) self._token_url = _https_url(self._required("token_url", token_url)) self._environment_id = environment_id or None @@ -552,11 +584,10 @@ def __init__( # same one, whichever kind started it. self._inflight: Optional[_Exchange] = None - # Seams for tests: the clock that decides freshness, and the sleeps + # Seams for tests: the clock that decides freshness, and the sleep # between exchange attempts. self._clock: Callable[[], float] = time.monotonic self._sleep: Callable[[float], None] = time.sleep - self._async_sleep: Callable[[float], Awaitable[None]] = asyncio.sleep @staticmethod def _required(field: str, value: Optional[str], env: Optional[str] = None) -> str: @@ -614,7 +645,7 @@ def resolve(self, *, timeout: Optional[float] = None) -> CredentialSnapshot: """ with self._lock: current = self._fresh() - exchange = None if current is not None else self._join_or_start() + exchange = None if current is not None else self._join_or_start(None) if exchange is not None: current = self._wait(exchange, timeout) assert current is not None @@ -628,7 +659,11 @@ async def aresolve(self, *, timeout: Optional[float] = None) -> CredentialSnapsh """ with self._lock: current = self._fresh() - exchange = None if current is not None else self._join_or_start_async() + exchange = ( + None + if current is not None + else self._join_or_start(asyncio.get_running_loop()) + ) if exchange is not None: current = await self._wait_async(exchange, timeout) assert current is not None @@ -676,35 +711,23 @@ def _store(self, token: str, lifetime: float) -> int: # --- shared exchange --- - def _can_join(self, exchange: _Exchange, *, blocking: bool) -> bool: - """Whether a caller can wait for ``exchange`` and count on an answer. Lock held. + def _join_or_start(self, loop: Optional[asyncio.AbstractEventLoop]) -> _Exchange: + """The exchange in progress, started if there is none. Lock held. - ``blocking`` is true for a synchronous caller, which blocks its thread - while it waits. + ``loop`` is the caller's event loop, or None for a synchronous caller. """ - task = exchange.task - if task is None: - # A thread runs it, whatever its waiters do. - return True - if task.done(): - # Canceled before it ran a single step, so it never settled. - return False - runner = task.get_loop() - if runner is _running_loop(): - # The caller is on the loop that runs the exchange. A coroutine - # that awaits lets it run. A blocked thread would stop it. - return not blocking - # Another thread's loop. It runs the exchange only while it is running. - return runner.is_running() - - def _join_or_start(self) -> _Exchange: - """The exchange in progress, started on a thread if there is none. Lock held.""" + if loop is None and self._provider_is_async: + # Nothing can await the provider for this caller, and waiting for + # an exchange that needs the caller's own thread to do so would + # never end. + raise WorkloadIdentityError("provider_failed", _ASYNC_PROVIDER_MESSAGE) exchange = self._inflight - if exchange is None or not self._can_join(exchange, blocking=True): - exchange = _Exchange(time.monotonic() + EXCHANGE_DEADLINE_SECONDS) + if exchange is None: + exchange = _Exchange(time.monotonic() + EXCHANGE_DEADLINE_SECONDS, loop) self._inflight = exchange try: - # Its own thread, not the first caller's: a caller that gives up + # Its own thread, not the first caller's thread or event loop: + # a caller that gives up, or a loop that is blocked or closed, # must not take the exchange down with it. threading.Thread( target=self._run_exchange, @@ -717,57 +740,14 @@ def _join_or_start(self) -> _Exchange: raise return exchange - def _join_or_start_async(self) -> _Exchange: - """The exchange in progress, started as a task if there is none. Lock held.""" - exchange = self._inflight - if exchange is None or not self._can_join(exchange, blocking=False): - exchange = _Exchange(time.monotonic() + EXCHANGE_DEADLINE_SECONDS) - # A task of its own, not the first caller's, for the same reason. - task = asyncio.get_running_loop().create_task( - self._run_exchange_async(exchange) - ) - exchange.task = task - # A task canceled before its first step never reaches its own - # ``except``; this settles the exchange for it. - task.add_done_callback(lambda _: self._settle_canceled(exchange)) - self._inflight = exchange - return exchange - def _run_exchange(self, exchange: _Exchange) -> None: try: - token, lifetime = self._exchange(exchange.deadline) + token, lifetime = self._exchange(exchange.deadline, exchange.loop) except BaseException as error: self._settle(exchange, error=error) return self._settle(exchange, token=token, lifetime=lifetime) - async def _run_exchange_async(self, exchange: _Exchange) -> None: - try: - try: - token, lifetime = await asyncio.wait_for( - self._exchange_async(exchange.deadline), EXCHANGE_DEADLINE_SECONDS - ) - except asyncio.TimeoutError: - raise WorkloadIdentityError( - "exchange_failed", _DEADLINE_DESCRIPTION - ) from None - except Exception as error: - self._settle(exchange, error=error) - except BaseException: - # Canceled, as when its event loop shuts down. Callers on other - # threads and loops may be waiting, so they are told. - self._settle_canceled(exchange) - raise - else: - self._settle(exchange, token=token, lifetime=lifetime) - - def _settle_canceled(self, exchange: _Exchange) -> None: - """Fail an exchange whose task ended without an outcome. No effect otherwise.""" - self._settle( - exchange, - error=WorkloadIdentityError("exchange_failed", _CANCELED_DESCRIPTION), - ) - def _settle( self, exchange: _Exchange, @@ -811,10 +791,9 @@ def _wait(self, exchange: _Exchange, timeout: Optional[float]) -> Tuple[str, int if time.monotonic() < overdue_at: # This caller's own timeout. The exchange is left alone. raise WorkOSTimeoutError(_WAIT_TIMEOUT_MESSAGE) - # The exchange outran its deadline: a provider that does not return (a - # thread cannot be interrupted), or a task whose event loop stopped. - # Give it up so the next caller starts a new exchange instead of - # waiting on this one. + # The exchange outran its deadline, which only a provider that does not + # return can cause: a thread cannot be interrupted. Give it up so the + # next caller starts a new exchange instead of waiting on this one. self._settle( exchange, error=WorkloadIdentityError("exchange_failed", _DEADLINE_DESCRIPTION), @@ -870,30 +849,28 @@ def _form(self, assertion: str) -> bytes: fields["scope"] = self._scope return urlencode(fields).encode("ascii") - def _provide(self) -> str: + def _provide( + self, loop: Optional[asyncio.AbstractEventLoop], run: _ExchangeRun + ) -> str: + """Call the provider on this thread, the exchange's own, and return its token. + + A plain callable may block (a file read, a cloud SDK call) without + stalling an event loop. What an asynchronous provider returns is + awaited on ``loop``, the event loop of the caller that started the + exchange. + """ result = self._provider() if inspect.isawaitable(result): - if inspect.iscoroutine(result): - result.close() - raise _AsyncProviderInSyncClient( - "The identity token provider is asynchronous. Use it with " - "AsyncWorkOSClient, or pass a synchronous provider." - ) - return _require_token(result) - - async def _provide_async(self) -> str: - provider = self._provider - if _is_coroutine_callable(provider): - result: object = await cast(Awaitable[str], provider()) - else: - # A plain callable may block (a file read, a cloud SDK call), so it - # runs in a worker thread and cannot stall the event loop. - result = await asyncio.to_thread(provider) - if inspect.isawaitable(result): - result = await result + if loop is None: + if inspect.iscoroutine(result): + result.close() + raise _AsyncProviderInSyncClient(_ASYNC_PROVIDER_MESSAGE) + result = _await_on(loop, result, run.time_left()) return _require_token(result) - def _exchange(self, deadline: float) -> Tuple[str, float]: + def _exchange( + self, deadline: float, loop: Optional[asyncio.AbstractEventLoop] + ) -> Tuple[str, float]: """Exchange the identity token, retrying per the SDK's retry policy. Retried: a provider failure, a transport failure, HTTP 429 and 5xx. The @@ -909,7 +886,7 @@ def _exchange(self, deadline: float) -> Tuple[str, float]: if attempt > 0: self._sleep(run.backoff(attempt)) try: - assertion = self._provide() + assertion = self._provide(loop, run) except _AsyncProviderInSyncClient as error: raise WorkloadIdentityError("provider_failed", str(error)) from None except Exception as error: @@ -930,32 +907,3 @@ def _exchange(self, deadline: float) -> Tuple[str, float]: if result is not None: return result raise run.exhausted() - - async def _exchange_async(self, deadline: float) -> Tuple[str, float]: - """Asynchronous twin of :meth:`_exchange`.""" - run = _ExchangeRun(deadline) - async with httpx2.AsyncClient(follow_redirects=False) as http: - backend = AsyncHttpxBackend(http) - for attempt in range(MAX_RETRIES + 1): - if attempt > 0: - await self._async_sleep(run.backoff(attempt)) - try: - assertion = await self._provide_async() - except Exception as error: - run.provider_failed(error) - continue - try: - response = await backend.request( - "POST", - self._token_url, - headers=_exchange_headers(), - content=self._form(assertion), - timeout=run.attempt_timeout(attempt), - ) - except TransportError as error: - run.transport_failed(error, self._token_url, assertion) - continue - result = run.read(response, assertion) - if result is not None: - return result - raise run.exhausted() diff --git a/tests/test_workload_identity.py b/tests/test_workload_identity.py index 24f7333f..073e0d91 100644 --- a/tests/test_workload_identity.py +++ b/tests/test_workload_identity.py @@ -25,6 +25,8 @@ import os import re import socket +import subprocess +import sys import threading import time import traceback @@ -364,13 +366,8 @@ def instrument( self, credentials: WorkloadIdentityCredentials ) -> WorkloadIdentityCredentials: """Give the credentials the fake clock and a sleeper that only records.""" - - async def record(seconds: float) -> None: - self.sleeps.append(seconds) - credentials._clock = self.clock.now credentials._sleep = self.sleeps.append - credentials._async_sleep = record return credentials def credentials( @@ -391,15 +388,14 @@ def bare_credentials( def watch_joins(self, credentials: WorkloadIdentityCredentials) -> Counter: """Count the callers that joined (or started) a shared exchange.""" joins = Counter() - for name in ("_join_or_start", "_join_or_start_async"): - original = getattr(credentials, name) + original = credentials._join_or_start - def joined(original: Callable[[], Any] = original) -> Any: - exchange = original() - joins.increment() - return exchange + def joined(loop: Optional[asyncio.AbstractEventLoop]) -> Any: + exchange = original(loop) + joins.increment() + return exchange - setattr(credentials, name, joined) + setattr(credentials, "_join_or_start", joined) return joins # clients @@ -1332,7 +1328,7 @@ def an_unreachable_token_endpoint_is_described_by_its_host_and_the_reason( (httpx2.ConnectError, untrusted, None), (httpx2.ConnectTimeout, "timed out", None), (httpx2.ReadTimeout, "The read operation timed out", None), - # A timeout in the asynchronous client has no text. + # A timeout with no text. (httpx2.ConnectTimeout, "", "timed out"), (httpx2.ReadTimeout, "", "timed out"), (httpx2.ReadError, "", "unknown network error"), @@ -1476,6 +1472,32 @@ def provider() -> str: stuck.set() +@scenario +def the_thread_of_an_exchange_ends_with_the_exchange(h: Harness) -> None: + credentials = h.credentials() + before = threading.enumerate() + h.token.hold() + + waiter = h.start(h.op_resolve(credentials)) + h.wait_until(h.token.entered.is_set) + started = [thread for thread in threading.enumerate() if thread not in before] + exchanging = [ + thread + for thread in started + if thread.name == "workos-workload-identity-exchange" + ] + assert len(exchanging) == 1 + # A daemon: an exchange in flight does not keep the interpreter alive. + assert exchanging[0].daemon + h.token.release() + snapshot = h.outcome(waiter) + + assert snapshot.headers["Authorization"] == "Bearer access-1" + exchanging[0].join(10) + assert not exchanging[0].is_alive() + assert credentials._inflight is None + + @scenario def credentials_can_be_resolved_without_a_client(h: Harness) -> None: credentials = h.credentials() @@ -1783,51 +1805,54 @@ def test_async_waiter_times_out_without_failing_the_exchange( assert h.token.count == 1 -def test_async_exchange_canceled_before_it_ran_does_not_block_the_next( +def test_an_exchange_outlives_the_caller_that_started_it( async_harness: AsyncHarness, ) -> None: h = async_harness credentials = h.credentials() + h.token.hold() - async def never_runs() -> None: - raise AssertionError("canceled before its first step") + async def start_an_exchange_and_be_canceled() -> Any: + starter = h.loop.create_task(credentials.aresolve()) + while not h.token.entered.is_set(): + await asyncio.sleep(0.001) + starter.cancel() + return (await asyncio.gather(starter, return_exceptions=True))[0] - stale = h.loop.create_task(never_runs()) - stale.cancel() - h.outcome(stale) - exchange = workload_identity._Exchange(time.monotonic() + 30) - exchange.task = stale - credentials._inflight = exchange + gave_up = h.loop.run_until_complete( + asyncio.wait_for(start_an_exchange_and_be_canceled(), 10) + ) + assert isinstance(gave_up, asyncio.CancelledError) + # The exchange it started is still the one in flight, and serves the next. + h.token.release() assert h.resolve(credentials).headers["Authorization"] == "Bearer access-1" + assert h.token.count == 1 -def test_an_async_exchange_canceled_before_it_ran_fails_its_waiters_at_once( - async_harness: AsyncHarness, +def test_an_exchange_does_not_need_the_event_loop_that_started_it( + network: Network, ) -> None: - h = async_harness - credentials = h.credentials() + provider = Provider() + credentials = WorkloadIdentityCredentials( + identity_token_provider=provider, client_id=CLIENT_ID, token_url=TOKEN_URL + ) + network.token.hold() - async def cancel_the_exchange_before_its_first_step() -> Any: - waiter = h.loop.create_task(credentials.aresolve()) - # One turn of the loop: the waiter has created the task that runs the - # exchange, and that task has not run yet. - await asyncio.sleep(0) - exchange = credentials._inflight - assert exchange is not None and exchange.task is not None - exchange.task.cancel() - return (await asyncio.gather(waiter, return_exceptions=True))[0] + async def give_up() -> None: + with pytest.raises(WorkOSTimeoutError): + await credentials.aresolve(timeout=0.05) - error = h.loop.run_until_complete( - asyncio.wait_for(cancel_the_exchange_before_its_first_step(), 10) - ) + # The loop that started the exchange is closed while the exchange waits + # for its response. + asyncio.run(give_up()) + assert network.token.entered.is_set() + network.token.release() - # Its waiter is told, and does not wait for the deadline to find out. - assert isinstance(error, WorkloadIdentityError) - assert error.code == "exchange_failed" - assert "canceled" in error.description - assert h.token.count == 0 - assert h.resolve(credentials).headers["Authorization"] == "Bearer access-1" + assert credentials.resolve().headers["Authorization"] == "Bearer access-1" + assert asyncio.run(credentials.aresolve()).generation == 1 + assert network.token.count == 1 + assert provider.calls == 1 def test_one_credentials_instance_serves_both_kinds_of_client( @@ -1882,7 +1907,7 @@ async def scene() -> List[Any]: return h.loop.run_until_complete(asyncio.wait_for(scene(), 10)) -def test_a_coroutine_joins_the_exchange_a_thread_runs( +def test_a_coroutine_joins_the_exchange_a_synchronous_caller_started( sync_harness: Harness, async_harness: Harness ) -> None: provider = Provider() @@ -1906,7 +1931,7 @@ def test_a_coroutine_joins_the_exchange_a_thread_runs( assert sync_harness.api.bearers() == ["access-1", "access-1"] -def test_a_thread_joins_the_exchange_a_task_runs( +def test_a_thread_joins_the_exchange_a_coroutine_started( sync_harness: Harness, async_harness: AsyncHarness ) -> None: provider = Provider() @@ -1953,13 +1978,14 @@ async def request() -> Any: assert h.api.bearers() == ["access-1", "access-1"] -def test_a_blocking_call_on_the_loop_that_runs_the_exchange_does_not_wait_for_it( +def test_a_blocking_call_on_the_event_loop_joins_the_exchange_a_coroutine_started( sync_harness: Harness, async_harness: AsyncHarness ) -> None: # A synchronous client called from a coroutine blocks the event loop. The - # exchange a task of that loop runs cannot finish until the call returns, - # so the call exchanges for itself instead of waiting for it. - credentials = async_harness.credentials() + # exchange runs on a thread of its own, so it finishes all the same, and + # the blocking call gets its token. + provider = Provider() + credentials = async_harness.credentials(provider) sync_client = sync_harness.client(credentials) async_client = async_harness.client(credentials) token = async_harness.token @@ -1980,11 +2006,129 @@ async def scene() -> List[Any]: outcomes = async_harness.loop.run_until_complete(asyncio.wait_for(scene(), 10)) assert outcomes == [{"ok": True}, {"ok": True}] - assert token.count == 2 - assert sorted(str(bearer) for bearer in async_harness.api.bearers()) == [ - "access-1", - "access-2", - ] + assert token.count == 1 + assert provider.calls == 1 + assert async_harness.api.bearers() == ["access-1", "access-1"] + + +def test_a_blocking_call_with_an_asynchronous_provider_fails_at_once( + sync_harness: Harness, async_harness: AsyncHarness +) -> None: + # The provider is awaited on the event loop, which the blocking call + # blocks. It is refused before it can wait for an exchange that needs + # that loop. + calls = Counter() + + async def provider() -> str: + calls.increment() + return "assertion-1" + + credentials = async_harness.credentials(provider) + sync_client = sync_harness.client(credentials) + async_client = async_harness.client(credentials) + token = async_harness.token + token.hold() + + async def scene() -> List[Any]: + first = async_harness.loop.create_task( + async_client.request("GET", ("organizations",)) + ) + while not token.entered.is_set(): + await asyncio.sleep(0.001) + with pytest.raises(WorkloadIdentityError) as refused: + sync_client.request("GET", ("organizations",)) + token.release() + return [refused.value, await first] + + refused, outcome = async_harness.loop.run_until_complete( + asyncio.wait_for(scene(), 10) + ) + + assert refused.code == "provider_failed" + assert "AsyncWorkOSClient" in refused.description + assert outcome == {"ok": True} + assert token.count == 1 + assert calls.value == 1 + + +def test_a_blocking_call_ends_at_the_deadline_when_the_provider_needs_the_loop_it_blocks( + sync_harness: Harness, async_harness: AsyncHarness +) -> None: + # A plain callable that returns an awaitable is known to be asynchronous + # only once it is called. A blocking call that joins such an exchange + # blocks the loop the awaitable needs. The exchange gives the provider + # until its deadline, then fails for everyone. No second one is started. + h = async_harness + h.monkeypatch.setattr(workload_identity, "EXCHANGE_DEADLINE_SECONDS", 0.3) + h.monkeypatch.setattr(workload_identity, "_DEADLINE_GRACE_SECONDS", 0.05) + entered = threading.Event() + calls = Counter() + + async def fetch() -> str: + entered.set() + await asyncio.Event().wait() + return "assertion-1" + + def provider() -> Any: + calls.increment() + return fetch() + + credentials = h.credentials(provider) + sync_client = sync_harness.client(credentials) + async_client = h.client(credentials) + + async def scene() -> List[Any]: + first = h.loop.create_task(async_client.request("GET", ("organizations",))) + while not entered.is_set(): + await asyncio.sleep(0.001) + started = time.monotonic() + with pytest.raises(WorkloadIdentityError) as blocked: + sync_client.request("GET", ("organizations",)) + waited = time.monotonic() - started + outcome = (await asyncio.gather(first, return_exceptions=True))[0] + return [blocked.value, waited, outcome] + + blocked, waited, outcome = h.loop.run_until_complete(asyncio.wait_for(scene(), 10)) + + assert blocked.code == "provider_failed" + assert "did not return before the exchange's deadline" in blocked.description + assert waited < 5 + # The asynchronous caller waited for the same exchange. + assert outcome is blocked + assert calls.value == 1 + assert h.token.count == 0 + + +def test_an_exchange_in_flight_does_not_keep_the_interpreter_alive() -> None: + script = """ +import threading + +from workos import WorkloadIdentityCredentials +from workos._errors import WorkOSTimeoutError + + +def provider() -> str: + threading.Event().wait() # never returns + return "" + + +credentials = WorkloadIdentityCredentials( + identity_token_provider=provider, + client_id="client_wif_test", + token_url="https://token.invalid/oauth2/token", +) +try: + credentials.resolve(timeout=0.05) +except WorkOSTimeoutError: + print("gave up with the exchange in flight") +""" + # The interpreter does not wait for the exchange's thread. + finished = subprocess.run( + [sys.executable, "-c", script], capture_output=True, text=True, timeout=30 + ) + + assert finished.returncode == 0, finished.stderr + assert finished.stdout.strip() == "gave up with the exchange in flight" # --- the real HTTP stack --------------------------------------------------------------- @@ -1996,15 +2140,10 @@ async def scene() -> List[Any]: def real_failure(token_url: str, asynchronous: bool) -> WorkloadIdentityError: """Exchange at ``token_url`` with nothing mocked, and return the error raised.""" - - async def no_sleep(seconds: float) -> None: - return None - credentials = WorkloadIdentityCredentials( client_id=CLIENT_ID, token_url=token_url, identity_token_provider=Provider() ) credentials._sleep = lambda seconds: None - credentials._async_sleep = no_sleep with pytest.raises(WorkloadIdentityError) as raised: if asynchronous: asyncio.run(credentials.aresolve()) @@ -2048,10 +2187,9 @@ def test_a_token_endpoint_that_refuses_the_connection_names_the_reason( # The number differs by platform: 111 on Linux, 61 on macOS. refused = f"[Errno {errno.ECONNREFUSED}] {os.strerror(errno.ECONNREFUSED)}" assert refused.endswith("Connection refused") - # The asynchronous client tries every address the host has and reports - # them as one failure. The operating system's error is not in its text. - reason = "All connection attempts failed" if asynchronous else refused - assert error.description == unreachable(reason, host=host) + # Both clients name the operating system's error: the exchange is sent + # the same way for both. + assert error.description == unreachable(refused, host=host) @both_clients @@ -2070,14 +2208,10 @@ def test_a_token_endpoint_that_does_not_answer_names_the_reason( error = real_failure(f"https://{host}/oauth2/token", asynchronous) - if asynchronous: - # The timeout has no text of its own here. - assert error.description == unreachable("timed out", host=host) - else: - # The interpreter's words, such as "The handshake operation timed out". - said = error.description - assert said.startswith(f"The request to the token endpoint at {host} failed: ") - assert said.endswith("timed out.") + # The interpreter's words, such as "The handshake operation timed out". + said = error.description + assert said.startswith(f"The request to the token endpoint at {host} failed: ") + assert said.endswith("timed out.") # --- configuration ------------------------------------------------------------------- From 1d5282d18498c47c866657e382022aea6d8c7952 Mon Sep 17 00:00:00 2001 From: "Garen J. Torikian" Date: Mon, 23 Nov 2026 16:50:34 -0500 Subject: [PATCH 21/24] fix(workload-identity): Keep the assertion out of the frames an error carries A token endpoint may repeat the assertion it was sent in `error` or `error_description`. The SDK already replaces it with `[redacted]` before it keeps either text, and cuts to 500 characters after that, so the error's code, description, message and repr never showed it. The error's traceback did. A traceback keeps the frames it passed through, and the frames of an exchange hold the assertion and the response in local variables: frame _exchange locals: assertion, response frame read locals: assertion, response, body, detail A tool that records the local variables of a traceback, such as an error reporter, would send them along. The exchange now empties the local variables of every frame in the tracebacks of the error it hands to its waiters, and of that error's causes. The frames and their line numbers stay. WIF-17 gains the two cases in which the token endpoint repeats the assertion: a 400 with it in `error_description`, and the same body on a 503 until the retries run out. Both leave the description as "JWT [redacted] failed validation". The case also checks every local variable of every frame in each error's tracebacks, as do the two tests of a repeated assertion. A new test shows that the assertion is replaced before the description is cut. --- src/workos/workload_identity.py | 18 ++++++++++ tests/test_workload_identity.py | 58 +++++++++++++++++++++++++++++++++ 2 files changed, 76 insertions(+) diff --git a/src/workos/workload_identity.py b/src/workos/workload_identity.py index 607407fe..a552c40a 100644 --- a/src/workos/workload_identity.py +++ b/src/workos/workload_identity.py @@ -36,6 +36,7 @@ import os import threading import time +import traceback from typing import ( Any, Awaitable, @@ -286,6 +287,22 @@ def _redact(text: str, secret: str) -> str: return text.replace(secret, "[redacted]") if secret else text +def _clear_frames(error: BaseException) -> None: + """Empty the local variables of every frame the tracebacks of ``error`` hold. + + A traceback keeps the frames it passed through, and the frames of an + exchange hold the assertion and what the server answered. Anything that + records the local variables of a traceback, such as an error reporter, + would find them there. The frames and their line numbers stay. + """ + seen: List[BaseException] = [] + current: Optional[BaseException] = error + while current is not None and current not in seen: + seen.append(current) + traceback.clear_frames(current.__traceback__) + current = current.__cause__ or current.__context__ + + def _lifetime(expires_in: object) -> float: """``expires_in`` in seconds, or the default when absent, not a number or not positive.""" if isinstance(expires_in, bool) or not isinstance(expires_in, (int, float)): @@ -744,6 +761,7 @@ def _run_exchange(self, exchange: _Exchange) -> None: try: token, lifetime = self._exchange(exchange.deadline, exchange.loop) except BaseException as error: + _clear_frames(error) self._settle(exchange, error=error) return self._settle(exchange, token=token, lifetime=lifetime) diff --git a/tests/test_workload_identity.py b/tests/test_workload_identity.py index 073e0d91..ca822452 100644 --- a/tests/test_workload_identity.py +++ b/tests/test_workload_identity.py @@ -639,6 +639,29 @@ def secrets_in(error: BaseException, *secrets: str) -> List[str]: return found +def locals_showing(error: BaseException, *secrets: str) -> List[str]: + """Every local variable, in the frames of an error's tracebacks, that shows a secret. + + This is what a tool that records the local variables of a traceback sees, + such as an error reporter. + """ + found: List[str] = [] + seen: List[BaseException] = [] + current: Optional[BaseException] = error + while current is not None and current not in seen: + seen.append(current) + frames = [frame for frame, _ in traceback.walk_tb(current.__traceback__)] + found.extend( + f"{type(current).__name__} {frame.f_code.co_name}() {name}: {secret}" + for frame in frames + for name, value in frame.f_locals.items() + for secret in secrets + if secret in repr(value) + ) + current = current.__cause__ or current.__context__ + return found + + def unreachable(reason: str, host: str = "token.test") -> str: """The whole description of a token request that got no HTTP response.""" return f"The request to the token endpoint at {host} failed: {reason}." @@ -1022,16 +1045,34 @@ def fail_with(provider: IdentityTokenProvider) -> None: # A second 401 from the API, after the access token was issued and sent. h.api.script.extend(unauthorized() for _ in range(2)) fail_with(Provider(assertion)) + # An OAuth error in which the token endpoint repeats the assertion. + repeated = { + "error": "invalid_grant", + "error_description": f"JWT {assertion} failed validation", + } + h.token.script.append(Reply(400, repeated)) + fail_with(Provider(assertion)) + # The same body on a 503, until the retries run out. + h.token.script.extend(Reply(503, repeated) for _ in range(EXCHANGE_ATTEMPTS)) + fail_with(Provider(assertion)) assert [type(error).__name__ for error in errors] == [ "WorkloadIdentityError", "WorkloadIdentityError", "WorkloadIdentityError", "AuthenticationError", + "WorkloadIdentityError", + "WorkloadIdentityError", ] assert h.api.bearers() == [access_token, access_token] + for error in errors[4:]: + assert isinstance(error, WorkloadIdentityError) + assert error.code == "invalid_grant" + assert error.description == "JWT [redacted] failed validation" for error in errors: assert secrets_in(error, assertion, access_token) == [] + # Nor in a local variable of any frame the error's traceback holds. + assert locals_showing(error, assertion, access_token) == [] for record in h.caplog.records: logged = f"{record.getMessage()} {record.__dict__!r}" assert assertion not in logged @@ -1309,6 +1350,7 @@ def an_assertion_echoed_by_the_server_is_redacted(h: Harness) -> None: assert error.code == "bad_[redacted]" assert error.description == "assertion [redacted] was rejected" assert secrets_in(error, assertion) == [] + assert locals_showing(error, assertion) == [] @scenario @@ -1404,6 +1446,22 @@ def an_assertion_in_a_transport_error_is_redacted(h: Harness) -> None: assert isinstance(error, WorkloadIdentityError) assert error.description == unreachable("could not send [redacted]") assert secrets_in(error, assertion) == [] + assert locals_showing(error, assertion) == [] + + +@scenario +def a_repeated_assertion_is_replaced_before_the_description_is_cut( + h: Harness, +) -> None: + assertion = "SECRET-ASSERTION-VALUE" + # Cut first, the 500 characters would end with the start of the assertion. + h.token.script.append(oauth_error("invalid_grant", "x" * 495 + assertion)) + + error = h.failure(h.op_resolve(h.credentials(Provider(assertion)))) + + assert isinstance(error, WorkloadIdentityError) + assert error.description == "x" * 495 + "[reda" + assert "SECRE" not in str(error) @scenario From c2125ef0e485f379f2034a4db4ae4e59a4004af1 Mon Sep 17 00:00:00 2001 From: "Garen J. Torikian" Date: Mon, 23 Nov 2026 16:50:35 -0500 Subject: [PATCH 22/24] fix(workload-identity): Make one bounded STS request per AWS provider call The AWS provider built its STS client with the AWS SDK's defaults. Measured against a local endpoint with boto3 1.44: - One provider call made 3 STS requests when STS answered with `Throttling` or with a 500, because the AWS SDK retries inside the client. - The client waited up to 60 seconds to connect and 60 seconds for each read. A provider does no retries: the WorkOS SDK calls the provider again as part of the token exchange, which has 30 seconds in all. The provider's client is now built with one attempt and with 10-second limits on connecting and on each wait for the response, the same limit the GitHub Actions and GCP providers use. One provider call is one STS request. The settings are on the provider's own client. They win over `AWS_MAX_ATTEMPTS`, `AWS_RETRY_MODE` and the shared config file, and change nothing for other AWS clients in the process. The credential chain, the region rule and the regional endpoint are as before. Tests: a loopback server stands in for STS, answers with `Throttling`, a 500 or a 503, and counts one request per provider call while `AWS_MAX_ATTEMPTS=5` is set. Another test reads the two limits from the client. The README of the package says that each call is one request. --- .../workos-workload-identity-aws/README.md | 2 + .../workos_workload_identity_aws/__init__.py | 17 +++- .../tests/test_aws_sts.py | 98 ++++++++++++++++++- 3 files changed, 113 insertions(+), 4 deletions(-) diff --git a/packages/workos-workload-identity-aws/README.md b/packages/workos-workload-identity-aws/README.md index af49da1d..742d457b 100644 --- a/packages/workos-workload-identity-aws/README.md +++ b/packages/workos-workload-identity-aws/README.md @@ -30,3 +30,5 @@ client = WorkOSClient( ``` `aws_sts(audience, region=None)` builds one STS client from the default AWS credential chain and returns a callable that requests an `RS256` token on every call. `region` is optional when boto3 can resolve one (`AWS_DEFAULT_REGION` or the shared config file); with no region, `aws_sts` raises. The request always goes to the regional STS endpoint. The audience must match the audience of the trust rule on your WorkOS application. + +Each call makes one STS request, with a 10-second limit on connecting and on waiting for the response. The AWS SDK's own retries are turned off on this client, because the WorkOS SDK retries the call as part of the token exchange. diff --git a/packages/workos-workload-identity-aws/src/workos_workload_identity_aws/__init__.py b/packages/workos-workload-identity-aws/src/workos_workload_identity_aws/__init__.py index 05ffed87..8e5835db 100644 --- a/packages/workos-workload-identity-aws/src/workos_workload_identity_aws/__init__.py +++ b/packages/workos-workload-identity-aws/src/workos_workload_identity_aws/__init__.py @@ -7,7 +7,8 @@ it to ``workos.WorkloadIdentityCredentials(identity_token_provider=...)``. The provider keeps no cache and does no retries; the WorkOS SDK retries the -call as part of the token exchange. +call as part of the token exchange. One call is one STS request: the AWS SDK's +own retries are turned off on the provider's client. """ from __future__ import annotations @@ -17,6 +18,7 @@ import boto3 import botocore.session +from botocore.config import Config from botocore.exceptions import BotoCoreError, ClientError, ReadTimeoutError from botocore.exceptions import ConnectionError as BotoConnectionError @@ -26,6 +28,8 @@ __all__ = ["AwsStsProviderError", "aws_sts"] _SIGNING_ALGORITHM = "RS256" +# For connecting to STS, and for each wait for its response. +_TIMEOUT_SECONDS = 10.0 _GLOBAL_ENDPOINT_HOSTS = ("sts.amazonaws.com",) @@ -71,8 +75,17 @@ def _create_sts_client(region: Optional[str]) -> "STSClient": "AWS_DEFAULT_REGION; sts:GetWebIdentityToken needs a regional STS " "endpoint." ) + # One request per call, and a limit on it. The AWS SDK would retry a + # throttled or failed request by itself, and waits 60 seconds by default. + # These are set on this client only, so they win over AWS_MAX_ATTEMPTS and + # the shared config file and change nothing for the rest of the process. + config = Config( + retries={"total_max_attempts": 1}, + connect_timeout=_TIMEOUT_SECONDS, + read_timeout=_TIMEOUT_SECONDS, + ) # The stubs type every service's client; only the STS one is installed. - client: STSClient = session.client("sts", region_name=resolved) # pyright: ignore[reportUnknownMemberType] + client: STSClient = session.client("sts", region_name=resolved, config=config) # pyright: ignore[reportUnknownMemberType] endpoint = client.meta.endpoint_url if any(endpoint.endswith(f"//{host}") for host in _GLOBAL_ENDPOINT_HOSTS): raise AwsStsProviderError( diff --git a/packages/workos-workload-identity-aws/tests/test_aws_sts.py b/packages/workos-workload-identity-aws/tests/test_aws_sts.py index 6be60205..5281d9db 100644 --- a/packages/workos-workload-identity-aws/tests/test_aws_sts.py +++ b/packages/workos-workload-identity-aws/tests/test_aws_sts.py @@ -9,17 +9,22 @@ The tests of an unreachable endpoint have no stub. The client sends its request, and the name lookup or the connection under it is faked, so nothing leaves the machine. + +The tests that count requests have no stub either: the stub answers before the +AWS SDK's retry logic runs. They point the client at a loopback server. """ from __future__ import annotations import datetime import errno +import http.server import os import socket import ssl +import threading from pathlib import Path -from typing import TYPE_CHECKING, Callable, List, Optional +from typing import TYPE_CHECKING, Callable, Iterator, List, Optional import pytest from botocore.stub import Stubber @@ -296,7 +301,7 @@ def no_answer(*args: object, **kwargs: object) -> None: raise TimeoutError("The read operation timed out") # A listener that never accepts: the connection opens through its backlog. - # The TLS handshake that would wait a minute for an answer is cut short. + # The TLS handshake that would wait ten seconds for an answer is cut short. monkeypatch.setattr(ssl.SSLContext, "wrap_socket", no_answer) with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as silent: silent.bind(("127.0.0.1", 0)) @@ -309,6 +314,95 @@ def no_answer(*args: object, **kwargs: object) -> None: assert str(excinfo.value) == unreachable("The read operation timed out") +class CountingSts: + """A loopback server that answers every request with one STS error, and counts them.""" + + def __init__(self) -> None: + self.status = 400 + self.code = "Throttling" + self.requests = 0 + counting = self + + class Handler(http.server.BaseHTTPRequestHandler): + def do_POST(self) -> None: + self.rfile.read(int(self.headers.get("Content-Length", 0))) + counting.requests += 1 + body = ( + "Sender" + f"{counting.code}no" + "request-1" + ).encode() + self.send_response(counting.status) + self.send_header("Content-Type", "text/xml") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, format: str, *args: object) -> None: + return None + + self._server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) + self._thread = threading.Thread( + target=self._server.serve_forever, + kwargs={"poll_interval": 0.01}, + daemon=True, + ) + self._thread.start() + + @property + def url(self) -> str: + return f"http://127.0.0.1:{self._server.server_address[1]}" + + def close(self) -> None: + self._server.shutdown() + self._server.server_close() + self._thread.join() + + +@pytest.fixture +def counting_sts(monkeypatch: pytest.MonkeyPatch) -> Iterator[CountingSts]: + server = CountingSts() + monkeypatch.setenv("AWS_ENDPOINT_URL_STS", server.url) + yield server + server.close() + + +@pytest.mark.parametrize( + ("status", "code"), + [(400, "Throttling"), (500, "InternalFailure"), (503, "ServiceUnavailable")], +) +def test_one_provider_call_is_one_sts_request( + counting_sts: CountingSts, + monkeypatch: pytest.MonkeyPatch, + status: int, + code: str, +) -> None: + counting_sts.status = status + counting_sts.code = code + # The AWS SDK's own settings ask for retries. The provider's client does + # not follow them: the WorkOS SDK retries the provider call itself. + monkeypatch.setenv("AWS_MAX_ATTEMPTS", "5") + monkeypatch.setenv("AWS_RETRY_MODE", "standard") + provider = aws_sts(AUDIENCE, region="us-east-1") + + with pytest.raises(AwsStsProviderError) as excinfo: + provider() + + assert str(excinfo.value) == f"sts:GetWebIdentityToken failed with {code}." + assert counting_sts.requests == 1 + + +def test_the_sts_client_waits_ten_seconds_at_most(sts: StubbedSts) -> None: + aws_sts(AUDIENCE, region="us-east-1") + + # The type stubs do not declare the settings of a client's configuration. + limits = vars(sts.clients[0].meta.config) + # To connect, and for each wait for the response. The AWS SDK's default + # is 60 seconds for both. + assert limits["connect_timeout"] == 10 + assert limits["read_timeout"] == 10 + + def test_audience_is_required() -> None: with pytest.raises(ValueError): aws_sts("", region="us-east-1") From d383085e0fe2511298d1e843d93c4f953e6cb5f1 Mon Sep 17 00:00:00 2001 From: "Garen J. Torikian" Date: Mon, 23 Nov 2026 17:00:32 -0500 Subject: [PATCH 23/24] fix(workload-identity): Run the exchange in the context of the caller that started it Commit 8de5545 moved every exchange to a thread of its own. A new thread starts with an empty context, so a provider that reads a context variable, such as one a web framework sets per request, found the variable's default or raised `LookupError`, and the exchange failed with `provider_failed`. For an asynchronous caller that was a step back: the task that ran the exchange copied the caller's context, and `asyncio.to_thread` passed it on to a blocking provider. A synchronous caller never had it. The thread now runs in a copy of the context of the caller that starts the exchange, for both kinds of client. An `async def` provider is scheduled from that thread, so the coroutine inherits the same copy on the caller's event loop. Callers that join an exchange do not change the context it runs in, as before. Tests: a provider that returns the value of a context variable, with both clients, and an `async def` provider that does the same after yielding to the event loop. Each makes one exchange with the value the caller set. --- src/workos/workload_identity.py | 12 +++++++--- tests/test_workload_identity.py | 40 +++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 3 deletions(-) diff --git a/src/workos/workload_identity.py b/src/workos/workload_identity.py index a552c40a..e3fa2ad8 100644 --- a/src/workos/workload_identity.py +++ b/src/workos/workload_identity.py @@ -31,6 +31,7 @@ import asyncio import concurrent.futures +import contextvars import inspect import math import os @@ -198,6 +199,8 @@ class IdentityTokenProvider(Protocol): A plain function may block: it runs on the exchange's own thread, never on an event loop. A coroutine function is awaited on the event loop of the asynchronous client that started the exchange (asynchronous client only). + Either way it runs in a copy of the context of the caller that started the + exchange, so it reads the context variables that caller set. """ def __call__(self) -> Union[str, Awaitable[str]]: ... @@ -745,10 +748,13 @@ def _join_or_start(self, loop: Optional[asyncio.AbstractEventLoop]) -> _Exchange try: # Its own thread, not the first caller's thread or event loop: # a caller that gives up, or a loop that is blocked or closed, - # must not take the exchange down with it. + # must not take the exchange down with it. The thread runs in + # a copy of that caller's context, so a provider that reads a + # context variable finds what the caller set. An asynchronous + # provider is scheduled from this thread and inherits the copy. threading.Thread( - target=self._run_exchange, - args=(exchange,), + target=contextvars.copy_context().run, + args=(self._run_exchange, exchange), name="workos-workload-identity-exchange", daemon=True, ).start() diff --git a/tests/test_workload_identity.py b/tests/test_workload_identity.py index ca822452..f28a1522 100644 --- a/tests/test_workload_identity.py +++ b/tests/test_workload_identity.py @@ -19,6 +19,7 @@ from __future__ import annotations import asyncio +import contextvars import errno import json import logging @@ -1530,6 +1531,24 @@ def provider() -> str: stuck.set() +@scenario +def a_provider_reads_the_context_of_the_caller_that_started_the_exchange( + h: Harness, +) -> None: + # Set by the caller, as a web framework does per request. The exchange + # runs on another thread, in a copy of the caller's context. + assertion: contextvars.ContextVar[str] = contextvars.ContextVar("assertion") + reset = assertion.set("assertion-from-the-context") + try: + h.get(h.client(h.credentials(assertion.get))) + finally: + assertion.reset(reset) + + assert h.token.forms()[0]["assertion"] == "assertion-from-the-context" + assert h.token.count == 1 + assert h.sleeps == [] + + @scenario def the_thread_of_an_exchange_ends_with_the_exchange(h: Harness) -> None: credentials = h.credentials() @@ -1809,6 +1828,27 @@ async def provider() -> str: assert threads == [threading.get_ident()] +def test_an_awaited_provider_reads_the_context_of_the_caller_too( + async_harness: Harness, +) -> None: + h = async_harness + assertion: contextvars.ContextVar[str] = contextvars.ContextVar("assertion") + + async def provider() -> str: + await asyncio.sleep(0) + return assertion.get() + + reset = assertion.set("assertion-from-the-context") + try: + h.get(h.client(h.credentials(provider))) + finally: + assertion.reset(reset) + + assert h.token.forms()[0]["assertion"] == "assertion-from-the-context" + assert h.token.count == 1 + assert h.sleeps == [] + + def test_async_client_awaits_a_callable_object_with_an_async_call( async_harness: Harness, ) -> None: From 3f19c0ca65b87c5154a5ea98a17a9d811d403671 Mon Sep 17 00:00:00 2001 From: "Garen J. Torikian" Date: Mon, 23 Nov 2026 17:12:18 -0500 Subject: [PATCH 24/24] test(workload-identity): Keep the test of a caller canceled right after it starts an exchange Commit 8de5545 replaced `test_async_exchange_canceled_before_it_ran_does_not_block_the_next`. The test was written for a task that is canceled before its first step, and there is no such task now. What it protected is a promise to the caller, and that still holds: a caller that is canceled right after it starts an exchange must not block the next caller or make it fail. The test is back under its name, written for the thread. A coroutine starts an exchange and is canceled while the exchange still waits for its provider, before any request to the token endpoint. The next caller then gets a token within its time limit, and the token endpoint has received one POST: the exchange went on without the caller that started it. `test_an_exchange_outlives_the_caller_that_started_it`, which cancels the caller while the request is in flight, stays. --- tests/test_workload_identity.py | 39 +++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/tests/test_workload_identity.py b/tests/test_workload_identity.py index f28a1522..024abc49 100644 --- a/tests/test_workload_identity.py +++ b/tests/test_workload_identity.py @@ -1903,6 +1903,45 @@ def test_async_waiter_times_out_without_failing_the_exchange( assert h.token.count == 1 +def test_async_exchange_canceled_before_it_ran_does_not_block_the_next( + async_harness: AsyncHarness, +) -> None: + h = async_harness + reached = threading.Event() + let_go = threading.Event() + + def provider() -> str: + reached.set() + assert let_go.wait(10), "the provider was never let go" + return "assertion-1" + + credentials = h.credentials(provider) + + async def start_an_exchange_and_be_canceled() -> Any: + starter = h.loop.create_task(credentials.aresolve()) + while not reached.is_set(): + await asyncio.sleep(0.001) + starter.cancel() + return (await asyncio.gather(starter, return_exceptions=True))[0] + + try: + # The caller that started the exchange is canceled while the exchange + # still waits for its provider, before it has made its request. + gave_up = h.loop.run_until_complete( + asyncio.wait_for(start_an_exchange_and_be_canceled(), 10) + ) + assert isinstance(gave_up, asyncio.CancelledError) + assert h.token.count == 0 + finally: + let_go.set() + + # The next caller neither hangs nor fails. The exchange went on without + # the caller that started it, and this one gets its token. + snapshot = h.loop.run_until_complete(asyncio.wait_for(credentials.aresolve(), 10)) + assert snapshot.headers["Authorization"] == "Bearer access-1" + assert h.token.count == 1 + + def test_an_exchange_outlives_the_caller_that_started_it( async_harness: AsyncHarness, ) -> None: