diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 55b028d58..61b9ccf63 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/.github/workflows/release-please.yml b/.github/workflows/release-please.yml index cb2f8111e..1f4129813 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 871bd6b3b..a169cdd4d 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,6 @@ { - ".": "10.9.0" + ".": "10.9.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/README.md b/README.md index c32132898..3f1ea9962 100644 --- a/README.md +++ b/README.md @@ -59,6 +59,127 @@ 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", # optional, see below + 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`. + +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) | +| `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). 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 + +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 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("/run/workos/identity-token") + +# 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 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. + +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: diff --git a/noxfile.py b/noxfile.py index 3c46b8c68..d313260e2 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 000000000..825c32f0d --- /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 000000000..67f8e4178 --- /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 000000000..742d457be --- /dev/null +++ b/packages/workos-workload-identity-aws/README.md @@ -0,0 +1,34 @@ +# 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. + +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/pyproject.toml b/packages/workos-workload-identity-aws/pyproject.toml new file mode 100644 index 000000000..54557d04e --- /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 000000000..e472c3368 --- /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 000000000..8e5835db7 --- /dev/null +++ b/packages/workos-workload-identity-aws/src/workos_workload_identity_aws/__init__.py @@ -0,0 +1,136 @@ +# @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. One call is one STS request: the AWS SDK's +own retries are turned off on the provider's client. +""" + +from __future__ import annotations + +import urllib.parse +from typing import TYPE_CHECKING, Callable, Optional + +import boto3 +import botocore.session +from botocore.config import Config +from botocore.exceptions import BotoCoreError, ClientError, ReadTimeoutError +from botocore.exceptions import ConnectionError as BotoConnectionError + +if TYPE_CHECKING: + from types_boto3_sts.client import STSClient + +__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",) + + +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``. + + 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." + ) + # 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, config=config) # 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 (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__}." + ) 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 000000000..e69de29bb 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 000000000..5281d9db2 --- /dev/null +++ b/packages/workos-workload-identity-aws/tests/test_aws_sts.py @@ -0,0 +1,408 @@ +# @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. + +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, Iterator, 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"} +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) +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() + + +@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 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)) + 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") + + +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") diff --git a/packages/workos-workload-identity-gcp/CHANGELOG.md b/packages/workos-workload-identity-gcp/CHANGELOG.md new file mode 100644 index 000000000..825c32f0d --- /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 000000000..67f8e4178 --- /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 000000000..f4948f32c --- /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 000000000..bc95e7af5 --- /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 000000000..e472c3368 --- /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 000000000..24d10fbf6 --- /dev/null +++ b/packages/workos-workload-identity-gcp/src/workos_workload_identity_gcp/__init__.py @@ -0,0 +1,129 @@ +# @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 http.client +import urllib.error +import urllib.parse +import urllib.request +from email.message import Message +from typing import IO, Callable, Tuple + +__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.""" + + +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.""" + + def redirect_request( + self, + req: urllib.request.Request, + fp: IO[bytes], + code: int, + msg: str, + headers: Message, + newurl: str, + ) -> None: + 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``. + + 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: + 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}." + ) + + 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 000000000..e69de29bb 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 000000000..c871aa759 --- /dev/null +++ b/packages/workos-workload-identity-gcp/tests/test_gcp_metadata.py @@ -0,0 +1,397 @@ +# @oagen-ignore-file + +"""Conformance cases WIF-GCP-01 to WIF-GCP-03, against a local mock server.""" + +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, Optional, Type + +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" +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: + """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 + 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() + + +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.""" + 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) 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 +) -> 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 + + +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")() + + 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 000000000..825c32f0d --- /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 000000000..67f8e4178 --- /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 000000000..8ad64c1fb --- /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 000000000..733004213 --- /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 000000000..e472c3368 --- /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 000000000..69a8193b5 --- /dev/null +++ b/packages/workos-workload-identity-github-actions/src/workos_workload_identity_github_actions/__init__.py @@ -0,0 +1,194 @@ +# @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 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, Tuple + +__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." +) +_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): + """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}." + ) + + +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 ``message`` shows no part of it. + """ + if any(not "!" <= char <= "~" for char in value): + raise GitHubActionsProviderError(message) + + +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.""" + 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="") + query = f"{parts.query}&{encoded}" if parts.query else encoded + 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``. + + 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) + # 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(request_token, _UNUSABLE_TOKEN_MESSAGE) + _require_visible_ascii(url, _UNUSABLE_URL_MESSAGE) + + status, body = _get(_with_audience(url, audience), request_token) + if status != 200: + raise GitHubActionsProviderError( + f"GitHub Actions OIDC token request failed with status {status}." + ) + + try: + payload = json.loads(body) + 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: + 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 000000000..e69de29bb 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 000000000..685fb8f1b --- /dev/null +++ b/packages/workos-workload-identity-github-actions/tests/test_github_actions.py @@ -0,0 +1,655 @@ +# @oagen-ignore-file + +"""Conformance cases WIF-GHA-01 and WIF-GHA-02, against a local mock endpoint.""" + +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, Optional, Type + +import pytest + +import workos_workload_identity_github_actions as gha +from workos_workload_identity_github_actions import ( + GitHubActionsProviderError, + github_actions, +) + +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. +# 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." +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: + """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 + 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() + + +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"}') + 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 shown(excinfo.value, REQUEST_TOKEN) == [] + + +@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)() + + # 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) + + +@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) == UNUSABLE_TOKEN + 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) == UNUSABLE_URL + 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(value: str, message: 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) + + 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 7a599a9c7..e81093ecc 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/release-please-config.json b/release-please-config.json index e6a27508c..1eeb30bee 100644 --- a/release-please-config.json +++ b/release-please-config.json @@ -1,9 +1,36 @@ { + "separate-pull-requests": true, + "bootstrap-sha": "6ec552607b8f0358176fa9910b2b22f484fb21ed", "packages": { ".": { "release-type": "python", "bump-minor-pre-major": true, "bump-patch-for-minor-pre-major": true, + "changelog-path": "CHANGELOG.md", + "exclude-paths": ["packages"] + }, + "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, + "changelog-path": "CHANGELOG.md" + }, + "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, + "changelog-path": "CHANGELOG.md" + }, + "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, "changelog-path": "CHANGELOG.md" } }, diff --git a/scripts/ci b/scripts/ci index edfa10151..37239a1e9 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/src/workos/__init__.py b/src/workos/__init__.py index fc234f954..c9e7a88b2 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 3cfedc3f0..12b55fb32 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, " @@ -317,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( @@ -325,6 +373,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 +403,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 +570,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 +593,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 +613,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 +680,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 +858,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 +877,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 +897,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 +964,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 000000000..1d154040a --- /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/session.py b/src/workos/session.py index 41dd71438..14624021e 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/src/workos/workload_identity.py b/src/workos/workload_identity.py new file mode 100644 index 000000000..e3fa2ad84 --- /dev/null +++ b/src/workos/workload_identity.py @@ -0,0 +1,933 @@ +# @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("/run/workos/identity-token"), + ) + ) + +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 + +import asyncio +import concurrent.futures +import contextvars +import inspect +import math +import os +import threading +import time +import traceback +from typing import ( + Any, + Awaitable, + Callable, + Dict, + List, + 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 ( + HTTPResponse, + HttpxBackend, + TransportError, + TransportTimeout, +) + +__all__ = [ + "ENVIRONMENT_ID_HEADER", + "IdentityTokenProvider", + "WorkloadIdentityCredentials", + "WorkloadIdentityError", + "token_env", + "token_file", +] + +# --- constants ------------------------------------------------------------------ + +# 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" +# 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 + +# The only environment variable the credentials read. +_CLIENT_ID_ENV = "WORKOS_CLIENT_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." +) +_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 --------------------------------------------------------------------- + +# 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 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 is not one the token endpoint accepts. Leave the " + "resource unset to use the default, https://api.workos.com." + ), + "invalid_client": ( + "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 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 " + "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: 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]]: ... + + +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 _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( + 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 _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)): + 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 _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: + # Some timeouts arrive 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 { + "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 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. + + 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, 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 = _redact(_unreachable(error, token_url), assertion) + 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 _Exchange: + """One in-flight exchange and its result, shared by every caller that waits for it. + + 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", "loop", "result", "settled", "wakers") + + def __init__( + self, deadline: float, loop: Optional[asyncio.AbstractEventLoop] + ) -> None: + self.deadline = deadline + # 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 + 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: + raise self.error + assert self.result is not None + return self.result + + +# --- 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. + + 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, 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 + environment variable the credentials read. No environment variable + switches workload identity on. + + 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. Required, and set only here: + no environment variable is read for it and there is no built-in + 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 + 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. 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; for ``client_id``, that is after + ``WORKOS_CLIENT_ID`` is consulted. The same code is raised when + ``token_url`` is not an absolute ``https`` URL. + """ + + 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 + # 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 + self._resource = resource or DEFAULT_RESOURCE + 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. + self._lock = threading.Lock() + self._token: Optional[str] = None + self._expires_at = -math.inf + self._lifetime = 0.0 + self._generation = 0 + # 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 sleep + # between exchange attempts. + self._clock: Callable[[], float] = time.monotonic + self._sleep: Callable[[float], None] = time.sleep + + @staticmethod + 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: + description = f"{field} is required" + if env: + description = f"{description} (or set {env})" + raise WorkloadIdentityError("invalid_configuration", description) + 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, an absolute ``https`` URL.""" + return self._token_url + + @property + 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 + 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(None) + 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() + 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 + 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: + headers = {"Authorization": f"Bearer {token}"} + if self._environment_id: + headers[ENVIRONMENT_ID_HEADER] = self._environment_id + return CredentialSnapshot( + headers=headers, + 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 --- + + def _join_or_start(self, loop: Optional[asyncio.AbstractEventLoop]) -> _Exchange: + """The exchange in progress, started if there is none. Lock held. + + ``loop`` is the caller's event loop, or None for a synchronous caller. + """ + 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: + exchange = _Exchange(time.monotonic() + EXCHANGE_DEADLINE_SECONDS, loop) + self._inflight = 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. 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=contextvars.copy_context().run, + args=(self._run_exchange, exchange), + name="workos-workload-identity-exchange", + daemon=True, + ).start() + except BaseException: + self._inflight = None + raise + return exchange + + 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) + + def _settle( + self, + exchange: _Exchange, + *, + 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. + + 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: + if self._inflight is exchange: + self._inflight = None + if exchange.settled: + return + exchange.settled = True + if token is not None: + 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: _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) + 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() + + 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: + 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: + 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 --- + + 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, 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 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, 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 + 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(loop, run) + 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, 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 new file mode 100644 index 000000000..024abc49d --- /dev/null +++ b/tests/test_workload_identity.py @@ -0,0 +1,2658 @@ +# @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. + +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 contextvars +import errno +import json +import logging +import os +import re +import socket +import subprocess +import sys +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 cryptography.fernet import Fernet + +from tests.generated_helpers import load_fixture +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 +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" +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_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) + + +@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}) + + +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.""" + credentials._clock = self.clock.now + credentials._sleep = self.sleeps.append + 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() + original = credentials._join_or_start + + def joined(loop: Optional[asyncio.AbstractEventLoop]) -> Any: + exchange = original(loop) + joins.increment() + return exchange + + setattr(credentials, "_join_or_start", 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 + + +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}." + + +# --- 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="orgs:write"))) + + assert h.token.count == 2 + scoped = h.token.requests[1] + assert scoped.form["scope"] == "orgs: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: + # (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())) + + 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_02_no_environment_id_sends_no_environment_header(h: Harness) -> None: + # (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 + ) + 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()) + + 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)) + # 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 + 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 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 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")) + 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) 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", IGNORED_URL) + h.monkeypatch.setenv("WORKOS_WIF_SCOPE", "scope_env") + before = h.token.count + 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 "scope" not in h.token.forms()[-1] + + # (d) An explicit client_id wins over the environment. + h.get( + h.client( + h.bare_credentials( + Provider(), client_id="client_explicit", token_url=TOKEN_URL + ) + ) + ) + assert h.token.forms()[-1]["client_id"] == "client_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 +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) == [] + assert locals_showing(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 with 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) == [] + 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 +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 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() + 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() + + 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() + + +# --- 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 ----------------------------------------------------------------- + + +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_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] = [] + + 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_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: + 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 + 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: + h = async_harness + credentials = h.credentials() + h.token.hold() + + 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] + + 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_exchange_does_not_need_the_event_loop_that_started_it( + network: Network, +) -> None: + provider = Provider() + credentials = WorkloadIdentityCredentials( + identity_token_provider=provider, client_id=CLIENT_ID, token_url=TOKEN_URL + ) + network.token.hold() + + async def give_up() -> None: + with pytest.raises(WorkOSTimeoutError): + await credentials.aresolve(timeout=0.05) + + # 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() + + 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( + 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", + ] + + +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_synchronous_caller_started( + 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_coroutine_started( + 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_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 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 + 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 == 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 --------------------------------------------------------------- + +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.""" + credentials = WorkloadIdentityCredentials( + client_id=CLIENT_ID, token_url=token_url, identity_token_provider=Provider() + ) + credentials._sleep = lambda seconds: None + 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") + # 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 +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) + + # 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 ------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("settings", "description"), + [ + ({"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, settings: Dict[str, str], description: str +) -> None: + with pytest.raises(WorkloadIdentityError) as caught: + WorkloadIdentityCredentials(identity_token_provider=Provider(), **settings) + + assert caught.value.code == "invalid_configuration" + assert caught.value.description == description + assert caught.value.hint == ( + "Workload identity credentials are missing a required setting." + ) + 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] +) -> None: + credentials = WorkloadIdentityCredentials( + identity_token_provider=Provider(), + client_id=CLIENT_ID, + token_url=TOKEN_URL, + environment_id=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 + + +@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: + 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_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." + ) diff --git a/uv.lock b/uv.lock index 5abdaf26c..3670d3eb1 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"